Mirza Translator gives you the ability to easily translate and manipulate text using the Yandex.Translate API.
Let's set this up real quick in just three mere steps!
-
Navigate to your Laravel installation folder via the terminal/cmd and run
composer require yak0d3/Mirza_Yandex_Translator
or add"yak0d3/Mirza_Yandex_Translator": "^1.0.0"
manually to yourcomposer.json
. -
Publish the configuration file using one of the following methods:
-
Add environment variable to your
.env
file with the nameYANDEX_API
and set its value to your own Yandex.Translate API Key. (e.g.YANDEX_API=MY_YANDEX_API_KEY
)
Note: You can get your FREE API Key from the Yandex.Translate Developers Dashboard
The quick usage guide is only meant to explain the basic usage of this package, for the list of methods and its relative information (Parameters, Return Type etc..) jump to the methods section or jump to the directives sections to view the list of available blade
directives.
-
{ "originalText": "Hello World!", "originalLanguage": "en", "text": { "es": "Hola Mundo!", "tr": "Merhaba D\u00fcnya!", "fr": "Bonjour Tout Le Monde!" } }
Note: You can decode this string by using the
json_decode
function.
[
{
"originalText": "Hello",
"translatedText": "Bonjour"
},
{
"originalText": "My dear",
"translatedText": "Mon cher"
},
{
"originalText": "Friend",
"translatedText": "Ami"
}
]
Note: You can decode this string by using the
json_decode
function.
Still not getting it? Take a look at the Documentation below and the confusion will go away!
Let's admin it, not everyone in here will find it easy to start using this package, so let's try to understand what's happening together. This section will cover the usage of each and every method provided by Mirza Yandex Translator, here is the table of contents:
- The
translate
method - The
translateArray
method - The
translateTo
method - The
detectLanguage
method - The
getSupportedLanguages
method - The
translateToAll
method - Blade directives
translate
methodExample:
$es_translation = Mirza::translate('Hello World!', 'es); //The first param is the text, the second one is the ISO code of the language
echo $es_translation; //This will output "Hola Mundo!"
translateArray
methodNote that all
json
strings needs to be decoded using the PHPjson_decode
function. Tip: To return a PHP array set the second argument ofjson_decode
totrue
(e.g.json_decode($jsonString, true);
).
If you prefer manipulatingjson objects
, leave the second argument empty or set it tofalse
.
Mirza::translateArray(['Hello', 'My Dear', 'Friend'],'fr');
this method translates a given array of text into which is in our case this array ['Hello', 'My Dear', 'Friend']
and translates it to a given language which is French in our example.
This function returns a json encoded
string like the following:
[
{
"originalText": "Hello",
"translatedText": "Bonjour"
},
{
"originalText": "My dear",
"translatedText": "Mon cher"
},
{
"originalText": "Friend",
"translatedText": "Ami"
}
]
As you can see, the output json string
is in the same order of the input array, now we can access each of these elements by decoding the string like so:
$jsonString = Mirza::translateArray(['Hello', 'My Dear', 'Friend'],'fr'); //The json string
$translationsArray = json_decode($jsonString, true); //Our PHP Array
$first_translation = $translationsArray[0]['translatedText'];
$second_translation = $translationsArray[1]['translatedText'];
$third_translation = $translationsArray[2]['translatedText'];
Easy, right? But it could get easier if you set the the $assoc parameter to true so you are able to access your string translations by their index names (that you have set manually). No body is getting confused in here, here is an example:
$textArray = [
'header' => "Welcome to the Mirza Documentation Page",
'body' => "The body is too long to be put in this item",
'footer' => "Thank you for reading this!"
]; //Our associative text array
$jsonString = Marzi::translate($textArray,'es', true); //Notice that i have set $assoc (third param) to `true`
$translationsArray = json_decode($jsonString, true);
//Now you can access the translations by their old index names
$header = $translationsArray['header']['translatedText'];
$body = $translationsArray['body']['translatedText'];
$footer = $translationsArray['footer']['translatedText'];
Note: If you set
$assoc
totrue
and provide a sequential array an exception will be thrown.
translateTo
method:This method is (maybe) the reverse version of the previous function, instead of taking an array
of strings, this method takes one string
and translates it to an array of languages.
Example:
$jsonString = Mirza::translateTo('My awesome text', ['ar', 'tr', 'de']);
The above example will return json string
with the following structure:
[
{
"originalText":"My awesome text",
"originalLanguage": "en",
"text":{
"ar":"\u0628\u0644\u062f\u064a \u0627\u0644\u0646\u0635 \u0631\u0647\u064a\u0628\u0629",
"tr":"M\u00fcthi\u015f metin",
"de":"Meine wunderbare text"
}
}
]
You may have noticed that some of the characters are in Unicode format, no worries if you
echo
it later on it will be displayed correctly.
Now we can easily decode this json string
and access our data like so:
$translations = json_decode($jsonString, true); //Our PHP array
$originalText = $translations['originalText'];
$originalLanguage = $translations['originalLanguage'];
$ar_translation = $translations['text']['ar'];
$tk_translation = $translations['text']['tr'];
$de_translation = $translations['text']['de'];
detectLanguage
methodYou sometimes need to detect in which language a text is written, the detectLanguage
method is made just for this matter!
As mentioned in the methods table, this method takes one required parameter and one optional.
The optional parameter (boolean $name
) lets us switch between returning the language ISO code or the language name.
Example:
-
Return language code:
//Leave the $name param empty or set it to `false`
//To return the language ISO code
$lang = Mirza::detectLanguage('Hello World!');
echo $lang; //Outputs "en"
-
Return language name:
//Setthe $name param to `true`
//To return the language ISO code
$lang = Mirza::detectLanguage('Hello World!', true);
echo $lang; //Outputs "English"
getSupportedLanguages
methodThis method takes no parameters (it should, but that will be added in a later version) and if executed it returns the list of all the supported languages.
Example:
//Save the json encoded string to the `$supportedLanguages` variable
$supportedLanguages = Mirza::getSupportedLanguages();
echo $supportedLanguages;
/* Outputs the json string in the following format:
[
{ 'lang_code' => 'lang_name' },
{ 'lang_code' => 'lang_name' },
]
*/
I didn't want to include the whole output because it is so long, but if you are still curious about it, i was prepared for this! Here is a screenshot:
Let's decode this json string
and play a little bit!
//Decode json string and wrap it into a PHP array
$langsArray = json_decode($supportedLanguages, true);
Let's say we have a language code, but we don't know to what language it refers, this line would help us a lot in such a case:
echo $langsArray['tr']; //Outputs "Turkish"
Now supposing that we have a language name, but we doesn't know the ISO code, EASY PEASY! We can do it with the PHP array_flip
function
$flippedArray = array_flip($langsArray);
/* The values are now keys! Cool right? */
$languageCode = $flippedArray['Sinhalese'];
echo $languageCode; //Outputs "si"
translateToAll
methodExample:
//Save the json string to a variable
$myStringInAllLanguages = Mirza::translateToAll('My string');
echo $myStringInAllLanguages;
/*Outputs a similar string to the `translateTo` method but
with all supported languages*/
-
@translate
: Allows you to translate a given text to a given language on the goExample:
@translate('Welcome', 'fr') <!-- Outputs "Bienvenue" -->
-
@yandex_rights
: If you have read the Yandex.Translate requirements for the use of translation results you'd know that this directive will be very useful.
You have to specify thecolor
as the first argument and thefont-size
as the second one.Example:
@yandex_rights('black', '16px'); <!-- Output --> <a href='https://translate.yandex.com/' target='_blank' style='font-size:16px;color:black;'>Powered by Yandex.Translate</a>
@languages_select
: Generates an HTML<select>
with the list of all supported languages.
Example:
@languages_select <!-- Output --> <select> <option value="lang_code">Lang_Name</option> <option value="lang_code">Lang_Name</option> <option value="lang_code">Lang_Name</option> </select>
Everything in Mirza is meant to be easy and readable, just by taking a look at the source code you will understand what's happening in no time. But don't worry, i have saved you the struggle and made a table containing the the list of methods that Mirza Translator provides.
Method | Parameters | Returns | Throws | Description |
---|---|---|---|---|
translate | string $text string $lang Optional: string $format [html|plain] (Default: "Plain") |
String | Exception: If text couldn't be translated. | Translates a given $text to a given $lang (language) |
translateTo | string $text array $langs |
String (json) | Exception: If one or more languages aren't supported. | Translate a given $text to multiple $langs (languages) |
translateArray | array $textArray string $lang Optional: bool $assoc (Default: false) |
String (json) | Exception: 1. If target language is not supported. 2. If $assoc is set to true and the given array is not associative. |
Translates a $textArray (array of text) to a given $lang (language) Note: If $assoc is set to true , the returned json string will have the same index names |
detectLanguage | string $text Optional: bool $langName |
String | Exception: 1. If language code is not found. 2. If language name is not found |
Detects the language of a given $text and returns the language code Note: If $langName is set to true , the language full name will be returned instead. |
getSupportedLanguages | None | String (json) | Exception: If an unknown error occurs while trying to fetch the list of supported functions | Returns a json string containing the list of all supported languages |
translateToAll | string $text |
String (json) | None | Translates a string ($text ) to all supported languages. Note: This may take a while and cause a PHP max_execution_time TIMEOUT Exception |
yandex_rights | Optional: string $color (Default: #fff) string $fontsize (Default: 14px) |
String | None | Returns the string of the "Powered By Yandex.Translate" link string. Also called via blade directive @yandex_rights . Note: Please refer to Yandex Translate: Requirements for the use of translation results to know more about font-size, color and placing requirements. |
languages_select | None | String | None | Returns the string of an HTML <select> tag with the list of all available languages. Also called via blade directive @languages_select |
Directive | Parameters | Description |
---|---|---|
@yandex_rights |
Optional: string $color (Default: #fff) string $fontsize (Default: 14px) |
Generates an HTML link for the "Powered By Yandex.Translate" text. |
@languages_select |
None | Generates an HTML <select> tag with the list of all available languages. |
@translate |
string $text string $lang |
Translate a given $text string to a given $lang (language) |
Mirza has been tested by only one person (obviously me 😃), which means that problems might occur with others, if something went wrong with your Mirza installation or you think something is still missing, please let me know by submitting a new issue.