Skip to content
Mirza Translator For Laravel gives you the ability to easily translate and manipulate text using the Yandex.Translate API.
PHP
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
config
src
tests
.travis.yml
CONTRIBUTING.md
LICENSE
README.md
composer.json
phpunit.xml.dist

README.md

Mirza Yandex Translator Logo

build Dependencies Code Quality

Mirza Yandex Translator For Laravel

Mirza Translator gives you the ability to easily translate and manipulate text using the Yandex.Translate API.

Table Of Contents

  1. Quick Start
  2. Quick Usage Guide
  3. Documentation
  4. Methods
  5. Blade Directives
  6. Issues & Suggestions
  7. License

Quick Start

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 your composer.json.

  • Publish the configuration file using one of the following methods:

    1. Run php artisan vendor:publish --provider="yak0d3\Mirza_Yandex_TranslatorT\MirzaServiceProvider"
    2. Run php artisan vendor:publish and type the number behind yak0d3\Mirza_Yandex_TranslatorT\MirzaServiceProvider then press Enter Publish configuration using php artisan vendor:publish
  • Add environment variable to your .env file with the name YANDEX_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

Quick Usage Guide

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.

  • Detect Language:
    Mirza::detectLanguage('Welcome');
    Output: en

  • Translate text:
    Mirza::translate('Hello','es');
    Output: "Hola"

  • Translate to Multiple Languages:
    Mirza::translateTo('Hello World!',['es', 'tr', 'fr']')

    Output:

     {
      "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.

  • Translate an Array of Text:
    $textArray = ['Hello','My Dear','Friend'];
    Mirza::translateArray($textArray,'fr');
    Output:

[
 {
 "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!

Documentation (With Examples)

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:

  1. The translate method
  2. The translateArray method
    1. Using sequential arrays
    2. Using associative arrays
  3. The translateTo method
  4. The detectLanguage method
    1. Return language code
    2. Return language name
  5. The getSupportedLanguages method
  6. The translateToAll method
  7. Blade directives
    1. @translate directive
    2. @yandex_rights directive
    3. @languages_select directive

1. The translate method
As you have already expected, for sure there is a `translate` method for a translator package, this method takes two parameters; the text and the ISO code of the target language.

Example:

	$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!"
2. The translateArray method

Note that all json strings needs to be decoded using the PHP json_decode function. Tip: To return a PHP array set the second argument of json_decode to true (e.g. json_decode($jsonString, true); ).
If you prefer manipulating json objects, leave the second argument empty or set it to false.

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 to true and provide a sequential array an exception will be thrown.

3. The 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'];
4. The detectLanguage method

You 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"
5. The getSupportedLanguages method

This 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: The list of supported Yandex.Translate languages

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"
6. The translateToAll method
I don't know what you might use this method for, but i thought it would be nice to include such a feature. As mentioned in the method name, this method translates a given string to all of the supported languages.

Example:

//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*/
7. Blade Directives
  • @translate: Allows you to translate a given text to a given language on the go

    Example:

     @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 the color as the first argument and the font-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>

Methods

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

Blade Directives

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)

Issues & Suggestions

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.

License

Mirza Yandex Translator MIT License

You can’t perform that action at this time.