Skip to content

Commit

Permalink
Refactor code and New Features. Major release candidate
Browse files Browse the repository at this point in the history
Replace TranslateFilesCommand::translate with Str::apiTranslate and Str::apiTranslateWithAttributes

New Features:
* Translate subfolder php translation files. #32 
* Yandex translate api support #21 
* Ability to add your own translation api


* first refactor commit

* remove .idea of phpstorm

* fixes

* refactor fix

* add roadmap remove tests

* refactors

* empty spaces fix and readme

* move line fn

* some refactor

* add ability to use own translator api

* now translates subfolders too + code refactor

* refactor messages

* custom translation api

* unit tests

* refactor

* add tests

* remove refator part
  • Loading branch information
tanmuhittin authored Jun 26, 2020
1 parent 42ca3a7 commit 329f078
Show file tree
Hide file tree
Showing 23 changed files with 724 additions and 445 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
/vendor
composer.lock
composer.lock
.idea/
docker-compose.yml
29 changes: 21 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,30 @@
# laravel-google-translate
Translate translation files (under /resources/lang) or lang.json files from specified base locale to other languages using stichoza/google-translate-php or Google Translate API https://cloud.google.com/translate/

* Translate translation files (under /resources/lang) or lang.json files
* Provide extra facade functions Str::apiTranslate and Str::apiTranslateWithAttributes

by using stichoza/google-translate-php or Google Translate API https://cloud.google.com/translate/ or Yandex Translatin API https://tech.yandex.com/translate/

## Str facade api-translation helpers
This package provides two translation methods for Laravel helper Str
* `Illuminate\Support\Str::apiTranslate` -> Translates texts using your selected api in config
* `Illuminate\Support\Str::apiTranslateWithAttributes` -> Again translates texts using your selected api in config
in addition to that this function ***respects Laravel translation text attributes*** like :name

## how to use your own translation api

* Create your own translation api class by implementing Tanmuhittin\LaravelGoogleTranslate\Contracts\ApiTranslatorContract
* Write your classname in config laravel_google_translate.custom_api_translator . Example : Myclass::class
* Write your custom apikey for your custom class in laravel_google_translate.custom_api_translator_key

Now all translations will use your custom api.

## this project needs refactor
Project code needs to be designed much better. Refactoring is in progress in refactor-code branch

## installation
```console
composer require tanmuhittin/laravel-google-translate --dev
composer require tanmuhittin/laravel-google-translate
php artisan vendor:publish --provider="Tanmuhittin\LaravelGoogleTranslate\LaravelGoogleTranslateServiceProvider"
```

Expand Down Expand Up @@ -37,12 +55,7 @@ This package can be used with https://github.com/andrey-helldar/laravel-lang-pub
* Add base Laravel translation files using https://github.com/andrey-helldar/laravel-lang-publisher
* Translate your custom files using this package

Done <br>

## todo
* Handle vendor translations too
* Prepare Web Interface
* Add other translation API support (Bing, Yandex...)
Done

## finally
Thank you for using laravel-google-translate :)
14 changes: 9 additions & 5 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
"php": ">=7.0.0",
"illuminate/support": "^5.5|^6|^7",
"illuminate/translation": "^5.5|^6|^7",
"stichoza/google-translate-php": "^4.0"
"stichoza/google-translate-php": "^4.0",
"google/cloud-translate": "dev-master",
"yandex/translate-api": "dev-master",
"ext-json": "*"
},
"extra": {
"laravel": {
Expand All @@ -31,9 +34,10 @@
"email": "[email protected]"
}
],
"minimum-stability": "dev",
"require-dev": {
"phpunit/phpunit": "^8.3@dev",
"ext-json": "*"
}
"phpunit/phpunit": "^8.3",
"orchestra/testbench": "5.x-dev"
},
"minimum-stability": "dev",
"prefer-stable": true
}
34 changes: 34 additions & 0 deletions src/Api/GoogleApiTranslate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace Tanmuhittin\LaravelGoogleTranslate\Api;

use Google\Cloud\Translate\V2\TranslateClient;
use Tanmuhittin\LaravelGoogleTranslate\Contracts\ApiTranslatorContract;

class GoogleApiTranslate implements ApiTranslatorContract
{
public $handle;

public function __construct($api_key)
{
$this->handle = new TranslateClient([
'key' => $api_key
]);

}

public function translate(string $text, string $locale, string $base_locale): string
{
if (is_null($base_locale))
$result = $this->handle->translate($text, [
'target' => $locale
]);
else
$result = $this->handle->translate($text, [
'source' => $base_locale,
'target' => $locale
]);

return $result['text'];
}
}
35 changes: 35 additions & 0 deletions src/Api/StichozaApiTranslate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace Tanmuhittin\LaravelGoogleTranslate\Api;


use Stichoza\GoogleTranslate\GoogleTranslate;
use Tanmuhittin\LaravelGoogleTranslate\Contracts\ApiTranslatorContract;

class StichozaApiTranslate implements ApiTranslatorContract
{
public $handle;

/**
* No need for an api_key
* @param null $api_key
*/
public function __construct($api_key = null)
{
$this->handle = new GoogleTranslate();
}

public function translate(string $text, string $locale, string $base_locale): string
{
if (is_null($base_locale))
$this->handle->setSource();
else
$this->handle->setSource($base_locale);
$this->handle->setTarget($locale);
try {
return $this->handle->translate($text);
} catch (\ErrorException $e) {
return false;
}
}
}
28 changes: 28 additions & 0 deletions src/Api/YandexApiTranslate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace Tanmuhittin\LaravelGoogleTranslate\Api;


use Tanmuhittin\LaravelGoogleTranslate\Contracts\ApiTranslatorContract;

class YandexApiTranslate implements ApiTranslatorContract
{
public $handle;


public function __construct($api_key)
{
$this->handle = new \Yandex\Translate\Translator($api_key);

}

public function translate(string $text, string $locale, string $base_locale): string
{
try {
$translation = $this->handle->translate($text, $base_locale . '-' . $locale);
} catch (\Exception $e) {
return false;
}
return $translation['text'][0]; //todo test if works Yandex code is old
}
}
106 changes: 106 additions & 0 deletions src/ApiTranslateWithAttribute.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<?php

namespace Tanmuhittin\LaravelGoogleTranslate;


use Tanmuhittin\LaravelGoogleTranslate\Contracts\ApiTranslatorContract;

class ApiTranslateWithAttribute
{
private $translator;

//api limit settings
private $request_count = 0;
private $request_per_sec = 5;
private $sleep_for_sec = 1;

private $parameter_map;

public function __construct()
{
$this->translator = resolve(ApiTranslatorContract::class);
}

/**
* Holds the logic for replacing laravel translation attributes like :attribute
* @param $base_locale
* @param $locale
* @param $text
* @return mixed|string
*/
public function translate($text, $locale, $base_locale = null)
{
$this->api_limit_check();

$text = $this->pre_handle_parameters($text);

$translated = $this->translator->translate($text, $locale, $base_locale);

$translated = $this->post_handle_parameters($translated);

return $translated;
}

/**
* Check if the API request limit reached.
*/
private function api_limit_check()
{
if ($this->request_count >= $this->request_per_sec) {
sleep($this->sleep_for_sec);
$this->request_count = 0;
}
$this->request_count++;
}


private function find_parameters($text)
{
preg_match_all("/(^:|([\s|\:])\:)([a-zA-z])+/", $text, $matches);
return $matches[0];
}


private function replace_parameters_with_placeholders($text, $parameters)
{
$parameter_map = [];
$i = 1;
foreach ($parameters as $match) {
$parameter_map ["x" . $i] = $match;
$text = str_replace($match, " x" . $i, $text);
$i++;
}
return ['parameter_map' => $parameter_map, 'text' => $text];
}

private function pre_handle_parameters($text)
{
$parameters = $this->find_parameters($text);
$replaced_text_and_parameter_map = $this->replace_parameters_with_placeholders($text, $parameters);
$this->parameter_map = $replaced_text_and_parameter_map['parameter_map'];
return $replaced_text_and_parameter_map['text'];
}

/**
* Put back parameters to translated text
* @param $text
* @return mixed
*/
private function post_handle_parameters($text)
{
foreach ($this->parameter_map as $key => $attribute) {
$combinations = [
$key,
substr($key, 0, 1) . " " . substr($key, 1),
strtoupper(substr($key, 0, 1)) . " " . substr($key, 1),
strtoupper(substr($key, 0, 1)) . substr($key, 1)
];
foreach ($combinations as $combination) {
$text = str_replace($combination, $attribute, $text, $count);
if ($count > 0)
break;
}
}
return str_replace(" :", " :", $text);
}
}
Loading

0 comments on commit 329f078

Please sign in to comment.