potsky / microsoft-translator-php-sdk
PHP SDK for Microsoft Translator
Installs: 115 877
Dependents: 1
Suggesters: 0
Security: 0
Stars: 16
Watchers: 4
Forks: 2
Open Issues: 1
Requires
- ext-curl: *
Requires (Dev)
- mockery/mockery: ^0.9
- phpunit/phpunit: ^5.0
- satooshi/php-coveralls: dev-master
This package is not auto-updated.
Last update: 2024-11-23 19:58:58 UTC
README
Table of content
1. Installation
Requirements
The SDK needs the cURL PHP extension.
With composer
Install the latest stable version using composer: composer require potsky/microsoft-translator-php-sdk
Or add potsky/microsoft-translator-php-sdk
to your composer.json
:
{ "require": { "potsky/microsoft-translator-php-sdk": "*" } }
Manually
Is it time to move to composer?
Not now? Ok, just include src/MicrosoftTranslator.php
in your PHP script :
include_once( 'src/MicrosoftTranslator.php' );
2. Configuration
2.1 Microsoft Account
-
Sign up for a Microsoft Azure account (credit card required)
If you don’t already have an Azure account, sign up for a Microsoft Azure account at http://azure.com.
-
After you have created an Azure account, subscribe to Azure. You will not be charged for Azure unless you use it. Then sign into the Azure portal at http://portal.azure.com.
-
Add a Microsoft Translator API subscription to your Azure account.
- Select the + New option
- Select AI + Cognitive Services from the list of Azure services
- Select either Translator Text API
- Press the Create button when you’re ready to create your Microsoft Translator API subscription.
- Complete the fields and press the Create button and you’re now subscribed to Microsoft Translator.
-
Retrieve your authentication key.
- Go to All Resources and select the Microsoft Translator API subscription account you are subscribed to.
- Select the Keys option and copy the first subscription key to access the service.
2.2 SDK
When instantiating a new client, you pass an array of configuration parameters:
$msTranslator = new MicrosoftTranslator\Client( $configuration );
Here is the list of available parameters, some are mandatory:
3. Usage
3.1 Methods
Define a client with your credentials:
<?php include 'src/MicrosoftTranslator.php'; $msTranslator = new \MicrosoftTranslator\Client( array( 'log_level' => \MicrosoftTranslator\Logger::LEVEL_DEBUG , 'api_client_key' => 'your-client-key' , ) );
Translate a text
Translate word chair
in german. The API will try to guess the input language:
print_r( $msTranslator->translate( 'chair' , 'de' )->getBody() );
Result:
Stuhl
Translate word chair
in german by specifying the initial sentence is in french:
print_r( $msTranslator->translate( 'chair' , 'de' , 'fr' )->getBody() );
Result:
Fleisch
Translate an array of texts
print_r( $msTranslator->translateArray( array( 'dog' , 'cat' ) , 'fr' )->getBody() );
Result:
Array
(
[dog] => chien
[cat] => chat
)
You can specify an input language as usual.
Transform a text
Only english is supported.
print_r( $msTranslator->TransformText( 'WTF I am not here!' , 'en' )->getBody() );
Result:
Array ( [ec] => 0 [em] => OK [sentence] => WHAT THE HECK I am not here! )
Detect the language of a text
print_r( $msTranslator->detect( 'The dog is red' )->getBody() );
Result:
en
Detect the language of an array of texts
print_r( $msTranslator->detectArray( array( 'The dog is red' , 'Le chien est rouge' ) )->getBody() );
Result:
Array ( [The dog is red] => en [Le chien est rouge] => fr )
Get language names
print_r( $msTranslator->getLanguageNames( 'fr' , array( 'en' , 'jp' , 'fr' ) )->getBody() );
Result:
Array ( [en] => Anglais [jp] => [fr] => Français )
Get available languages for translation
print_r( $msTranslator->getLanguagesForTranslate()->getBody() );
Result:
Array ( [0] => ar [1] => bs-Latn [2] => bg [3] => ca [4] => zh-CHS [5] => zh-CHT [6] => hr [7] => cs [8] => da [9] => nl ... )
Break sentences
print_r( $msTranslator->breakSentences( 'The dog is red. The cat is blue. The fish is yellow submarine.' , 'en' )->getBody() );
Result:
Array ( [0] => The dog is red. [1] => The cat is blue. [2] => The fish is yellow submarine. )
3.2 Handle errors
SDK can throw an MicrosoftTranslator\Exception
in several cases :
- HTTP problems with cURL
- API problems...
- Wrong credentials
- ...
You should catch these errors like this:
try { ... } catch ( \MicrosoftTranslator\Exception $e ) { $error = sprintf( "Error #%s with message : %s" , $e->getCode() , $e->getMessage() ); $msg = sprintf( "| %s |" , $error ); $line = str_repeat( '-' , strlen( $msg ) ); echo sprintf( "%s\n%s\n%s\n" , $line , $msg , $line ); }
or like this by checking the returned code instead:
try { ... } catch ( \MicrosoftTranslator\Exception $f ) { if ( $f->getCode() === 500 ) { echo sprintf( "Oups, error #%s : %s." , $f->getCode() , $f->getMessage() ); } else { echo sprintf( "Error #%s : %s\n" , $f->getCode() , $f->getMessage() ); } }
3.3 Customize the SDK
You can use your own classes to implement several parts of the SDK. Your classes need to implement interfaces and they will get the configuration array in the constructors. You can then customize your classes at runtime.
3.3.1 Inject a new Logger
You can use your own Logger
class. The Logger
class is used to log SDK messages.
It must implement the \MicrosoftTranslator\LoggerInterface
interface.
Then use it when instantiating a client:
$msTranslator = new \MicrosoftTranslator\Client( $config , null , null , $my_logger );
3.3.2 Inject a new HTTP manager
You can use your own Http
class. The Http
class manages the HTTP connexions to reach the accumulator API.
It must implement the \MicrosoftTranslator\HttpInterface
interface.
Then use it when instantiating a client:
$msTranslator = new \MicrosoftTranslator\Client( $config , $my_http_manager );
3.3.3 Inject a new Auth manager
You can use your own Auth
class. The Auth
class responsibility is to get an access token and to give it to the Guard
manager.
It must implement the \MicrosoftTranslator\AuthInterface
interface.
Then use it when instantiating a client:
$msTranslator = new \MicrosoftTranslator\Client( $config , null , $my_auth_manager );
3.3.4 Inject a new Guard manager
You can use your own Guard
manager. The Guard
class responsibility is to store access tokens and to manage expiration durations.
The Guard
injection is a little bit different of others injections because it is done in the configuration array. This is a setter dependency injection instead of an instantiation dependency injection.
It must implement the \MicrosoftTranslator\GuardInterface
interface.
Inject a new Guard
manager via the configuration array:
$msTranslator = new \MicrosoftTranslator\Client( array( 'guard_type' => 'MyNameSpace\\MyGuard' ) );
3.4 Manage saved access tokens
The SDK maintains access tokens via a Guard object. The default Guard is a GuardFile which stores access tokens in files.
If you need to delete all saved access token, you can do this:
$msTranslator->getAuth()->getGuard()->deleteAllAccessTokens();
To delete only expired access tokens, run this:
$msTranslator->getAuth()->getGuard()->cleanAccessTokens();
4. Change Log
v0.0.3
- Switch to Azure API
- Add an example ready to use in the
example
directory
v0.0.2
- The SDK now returns a
MicrosoftTranslator\Exception
when access token cannot be retrieved
- The SDK now returns a
v0.0.1
- here is the beginning
5. Contribute
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Added some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request
Tests are in tests
. To run the tests: vendor/bin/phpunit
.
Coverage cannot decrease next a merge. To track file coverage, run vendor/bin/phpunit --coverage-html coverage
and open coverage/index.html
to check uncovered lines of code.