Skip to content

Commit

Permalink
changes to class structure, now supports multiple language translatio…
Browse files Browse the repository at this point in the history
…ns at once
  • Loading branch information
kevinjavitz committed Nov 1, 2016
1 parent da704d3 commit 66d6dcf
Show file tree
Hide file tree
Showing 3 changed files with 162 additions and 71 deletions.
Empty file added i18n/blank.txt
Empty file.
84 changes: 13 additions & 71 deletions translate.php
Original file line number Diff line number Diff line change
@@ -1,29 +1,11 @@
<?php

require('vendor/autoload.php');
require('translateclass.php');
use League\Csv\Reader;

/**
* Load Google API Instance
*/
$client = new Google_Client();

$client->setApplicationName("Client_Library_Examples");
// Set your developer key here, make sure it is enabled for domain you are using this from
// and Google Translate API
// https://console.developers.google.com
$client->setDeveloperKey("");
$service = new Google_Service_Translate($client);

/**
* Get list of languages we can translate to
*/
$sourceLanguage = 'en';
$filewritesuccess = '';
$langavailable = $service->languages;
$languages = $langavailable->listLanguages(['target' => $sourceLanguage]);
$languagesArray = $languages['data']['languages'];
$linesToProcess = 50; // how many lines of the csv to process in one translation request. Google limits to 2000 chars.
$translater = new Translateclass();
$languagesArray = $translater->getLanguagesAvailable();

/**
* Process form if submitted
Expand All @@ -48,59 +30,19 @@
* line by line in the csv file
*/

$handle = fopen($filetmp, 'r');
$translateArray = [];
$reader = Reader::createFromPath($filetmp);
$reader = $reader->fetchAll();
$curRow = 0;
$totalRows = (int)count($reader);
$textToTranslateArray = [];
$originalCSVLanguageArray = [];
$translatedTextArray = [];

function processTranslations($service, $textToTranslateArray, $sourceLanguage){
$translations = $service->translations;
$destinationLanguage = $_POST['language'];
$translated = $translations->listTranslations($textToTranslateArray, $destinationLanguage, ['source' => $sourceLanguage]);
return $translated['data']['translations'];
}

for($curRow;$curRow<$totalRows;$curRow++) {
$textToTranslateArray[] = $reader[$curRow][0];
$originalCSVLanguageArray[] = $reader[$curRow][0];
if(($curRow != 0 && (($curRow % $linesToProcess) == 0)) || // if we are in a multiple of lines to process
(($curRow + 1) == $totalRows)){ //
$translationsArray = processTranslations($service, $textToTranslateArray, $sourceLanguage);
$translatedTextArray = array_merge($translatedTextArray, $translationsArray);
$textToTranslateArray = []; // reset
}
// while (($data = fgetcsv($handle)) !== false) {
// $textToTranslateArray[] = $data[0];
// }
}



// debug translate Array
// $translateArray = ['hello how are you', 'i have a dog'];



/**
* Re-Assemble CSV file from the translations
* Go through each language and generate the CSV language files
*/
$len = count($translatedTextArray);
$fileText = '';
for ($i = 0; $i < $len; $i++) {
// format is 'text to translate','translated text'
$fileText .= '"' . $originalCSVLanguageArray[$i] . '","' . $translatedTextArray[$i]['translatedText'] . '"' . PHP_EOL;

foreach($_POST['language'] as $language){
$translatedTextArray = $translater->processTranslationByRow($reader, $language);
$languageCode = $translater->getMageLanguageCode($language);
$translater->generateCSV($translatedTextArray, $languageCode);
}
$newfile = fopen($file_name, 'w') or die("Unable to open file!");
if (fwrite($newfile, $fileText)){
$filewritesuccess = "File created successfully at: " . getcwd() . DIRECTORY_SEPARATOR . $file_name;
};
fclose($newfile);
//var_dump($translated);

}

//var_dump($translated);
Expand All @@ -113,14 +55,14 @@ function processTranslations($service, $textToTranslateArray, $sourceLanguage){
<div class="page-header">
<h1>Magento 2 Language File CSV Translator</h1>
</div>
<?php if($filewritesuccess != ''){
?><div class="alert alert-success" role="alert"><?php echo $filewritesuccess; ?></div>
<?php if($translater->filewritesuccess != ''){
?><div class="alert alert-success" role="alert"><?php echo $translater->filewritesuccess; ?></div>
<?php
}
?>
<form method="post" enctype="multipart/form-data">
<label for="languages">Translate language file to: </label>
<select name="language">
<select multiple="multiple" name="language[]" size="15">
<?php
foreach ($languagesArray as $language) {
echo '<option value=' . $language['language'] . '>' . $language['name'] . '</option>';
Expand Down
149 changes: 149 additions & 0 deletions translateclass.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
<?php
require('vendor/autoload.php');
use League\Csv\Reader;

class Translateclass {

/**
* language code to Magento language code array
* this list is not complete, just the most common ones we translate for
* Mage 2 locales list is at Magento\Framework\Locale\Config.php
*/

public $languageToMageLanguage = [
'af' => 'af_ZA',
'ar' => 'ar_SA',
'be' => 'be_BY',
'da' => 'da_DK',
'de' => 'de_DE',
'el' => 'el_GR',
'es' => 'es_ES',
'fr' => 'fr_FR',
'hr' => 'hr_HR',
'id' => 'id_ID',
'it' => 'it_IT',
'iw' => 'he_IL',
'ja' => 'ja_JP',
'ko' => 'ko_KR',
'nl' => 'nl_NL',
'pt' => 'pt_BR',
'ro' => 'ro_RO',
'ru' => 'ru_RU',
'th' => 'th_TH',
'tl' => 'fil_PH',
'sv' => 'sv_SE',
'uk' => 'uk_UA',
'vi' => 'vi_VN',
'zh' => 'zh_Hans_CN'
];

protected $i18ndir = 'i18n';

/**
* How many lines of the csv to process in one translation request. Google limits to 2000 chars.
*
* @var int
*/
protected $linesToProcess = 50;

protected $sourcelanguage = 'en';

public $filewritesuccess = '';

protected $originalCSVLanguageArray = [];


/**
* Load Google API Instance
*/
public function __construct()
{
$this->client = new Google_Client();
$this->client->setApplicationName("Client_Library_Examples");
// Set your developer key here, make sure it is enabled for domain you are using this from
// and Google Translate API
// https://console.developers.google.com
$this->client->setDeveloperKey("");
$this->service = new Google_Service_Translate($this->client);
}

/**
* Gets languages available and returns them as an array
*
* @return mixed
*/
public function getLanguagesAvailable(){
$langavailable = $this->service->languages;
$languages = $langavailable->listLanguages(['target' => $this->sourcelanguage]);
return $languages['data']['languages'];
}

public function processTranslationByRow($reader, $destinationLanguage){
$totalRows = (int)count($reader);
$translatedTextArray = [];
for($curRow=0;$curRow<$totalRows;$curRow++) {
$textToTranslateArray[] = $reader[$curRow][0];
/**
* original CSV language array used later for rebuilding first column of CSV
*/
if(count($this->originalCSVLanguageArray)<= $totalRows) {
$this->originalCSVLanguageArray[] = $reader[$curRow][0];
}
if(($curRow != 0 && (($curRow % $this->linesToProcess) == 0)) || // if we are in a multiple of lines to process
(($curRow + 1) == $totalRows)){ //
$translationsArray = $this->processTranslations($textToTranslateArray, $destinationLanguage);
$translatedTextArray = array_merge($translatedTextArray, $translationsArray);
$textToTranslateArray = []; // reset
}
}
return $translatedTextArray;
}

/**
* Takes a source array and translates to the destination language
*
* @param $textToTranslateArray
* @param $sourceLanguage
* @return mixed
*/
public function processTranslations($textToTranslateArray, $destinationLanguage){
$translations = $this->service->translations;
$translated = $translations->listTranslations($textToTranslateArray, $destinationLanguage, ['source' => $this->sourcelanguage]);
return $translated['data']['translations'];
}

/**
* Searches languages array and returns the Mage language code
*
* @param $language
* @param $languageToMageLanguage
* @return mixed
*/
public function getMageLanguageCode($language){
if(array_key_exists($language, $this->languageToMageLanguage)){
return $this->languageToMageLanguage[$language];
} else {
return $language;
}
}

/**
* Re-Assemble CSV file from the translations
*/
public function generateCSV($translatedTextArray, $languageCode)
{
$len = count($translatedTextArray);
$fileText = '';
$file_name = $languageCode . '.csv';
for ($i = 0; $i < $len; $i++) {
// format is 'text to translate','translated text'
$fileText .= '"' . $this->originalCSVLanguageArray[$i] . '","' . $translatedTextArray[$i]['translatedText'] . '"' . PHP_EOL;
}
$newfile = fopen($this->i18ndir . DIRECTORY_SEPARATOR . $file_name, 'w') or die("Unable to open file!");
if (fwrite($newfile, $fileText)) {
$this->filewritesuccess .= "File created successfully at: " . getcwd() . DIRECTORY_SEPARATOR . $this->i18ndir . DIRECTORY_SEPARATOR . $file_name . "<br />";
};
fclose($newfile);
}

}

0 comments on commit 66d6dcf

Please sign in to comment.