From 3eca04aef44f99de4d71fc12bb1197fb7ac96a6a Mon Sep 17 00:00:00 2001 From: Muhittin Tan Date: Fri, 29 Mar 2019 15:28:05 +0300 Subject: [PATCH] translate without api key trait added (#2) Translate without API key using stichoza/google-translate-php --- composer.json | 3 ++- src/commands/TranslateFilesCommand.php | 30 +++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 510b945..e2f02de 100644 --- a/composer.json +++ b/composer.json @@ -5,7 +5,8 @@ "illuminate/console": ">=5.1", "php": ">=7.0.0", "illuminate/support": "5.5.x|5.6.x|5.7.x|5.8.x", - "illuminate/translation": "5.5.x|5.6.x|5.7.x|5.8.x" + "illuminate/translation": "5.5.x|5.6.x|5.7.x|5.8.x", + "stichoza/google-translate-php": "dev-master" }, "extra": { "laravel": { diff --git a/src/commands/TranslateFilesCommand.php b/src/commands/TranslateFilesCommand.php index 88fe4db..5d8c8dc 100644 --- a/src/commands/TranslateFilesCommand.php +++ b/src/commands/TranslateFilesCommand.php @@ -3,7 +3,8 @@ namespace Tanmuhittin\LaravelGoogleTranslate\Commands; use Illuminate\Console\Command; -use Symfony\Component\Finder\Finder; //require +use Stichoza\GoogleTranslate\GoogleTranslate; +use Symfony\Component\Finder\Finder; class TranslateFilesCommand extends Command { @@ -89,6 +90,33 @@ public function handle() */ private function translate($text, $locale) { + if(config('laravel_google_translate.google_translate_api_key')){ + return self::translate_via_api_key($text, $locale); + }else{ + return self::translate_via_stichoza($text, $locale); + } + } + + /** + * @param $text + * @param $locale + * @return null|string + * @throws \ErrorException + */ + private function translate_via_stichoza($text,$locale){ + $tr = new GoogleTranslate(); + $tr->setSource($this->base_locale); + $tr->setTarget($locale); + return $tr->translate($text); + } + + /** + * @param $text + * @param $locale + * @return mixed + * @throws \Exception + */ + private function translate_via_api_key($text, $locale){ $apiKey = config('laravel_google_translate.google_translate_api_key'); $url = 'https://www.googleapis.com/language/translate/v2?key=' . $apiKey . '&q=' . rawurlencode($text) . '&source=' . $this->base_locale . '&target=' . $locale; $handle = curl_init();