Skip to content

Commit

Permalink
Fix multiple sentence parser bug
Browse files Browse the repository at this point in the history
  • Loading branch information
relliv committed Sep 18, 2022
1 parent 36c234a commit 2143c47
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
1 change: 0 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
"description": "Simple Google Translate API implementation without key",
"type": "library",
"license": "MIT",
"version": "1.1.0",
"keywords": [
"laravel",
" translate",
Expand Down
24 changes: 17 additions & 7 deletions src/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public static function translate(string $text, string $sourceLang, string $trans
$contentHash = hash('md5', $text);
$cahceKey = "open:translate:keyword:{$contentHash}:{$sourceLang}:{$translateLang}";
$isCachingenabled = Config::get('open-google-translate.use_cache', true);
$finalTranslation = null;

if ($isCachingenabled === true && Cache::has($cahceKey)) {
return Cache::get($cahceKey);
Expand All @@ -50,17 +51,26 @@ public static function translate(string $text, string $sourceLang, string $trans
if ($response->successful()) {
$response = $response->json();

if (isset($response[0][0][0]) && !empty($response[0][0][0])) {
if ($isCachingenabled === true) {
Cache::put($cahceKey, $response[0][0][0], Date::now()->addMinutes(
Config::get('open-google-translate.cache_minutes', 60 * 24 * 7)
));
// probably there is a valid result
if (isset($response[0])) {
$result = $response[0];

// if there is more than one sentence, we will take each one and join them
if (is_array($result) && count($result) > 0) {
$finalTranslation = collect($result)
->map(fn ($result) => $result[0] ?? null)
->filter(fn ($result) => $result !== null)
->join('');
}
}

return $response[0][0][0];
if (!empty($finalTranslation) && $isCachingenabled === true) {
Cache::put($cahceKey, $finalTranslation, Date::now()->addMinutes(
Config::get('open-google-translate.cache_minutes', 60 * 24 * 7)
));
}
}

return null;
return $finalTranslation;
}
}

0 comments on commit 2143c47

Please sign in to comment.