Skip to content

Commit

Permalink
chore: automatically translate empty strings (monicahq/chandler#498)
Browse files Browse the repository at this point in the history
  • Loading branch information
djaiss committed May 10, 2023
1 parent 768e935 commit a91f3cb
Show file tree
Hide file tree
Showing 4 changed files with 142 additions and 10 deletions.
49 changes: 49 additions & 0 deletions app/Console/Commands/MonicaLocalize.php
Expand Up @@ -3,9 +3,14 @@
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
use Stichoza\GoogleTranslate\GoogleTranslate;
use Symfony\Component\Finder\Finder;

class MonicaLocalize extends Command
{
private GoogleTranslate $googleTranslate;

/**
* The name and signature of the console command.
*
Expand All @@ -28,5 +33,49 @@ public function handle(): void
$locales = config('localizer.supported-locales');
array_shift($locales);
$this->call('localize', ['lang' => implode(',', $locales)]);

$this->loadTranslations($locales);
}

/**
* Heavily inspired by https://stevensteel.com/blog/automatically-find-translate-and-save-missing-translation-keys
*/
private function loadTranslations(array $locales): void
{
$path = lang_path();
$finder = new Finder();
$finder->in($path)->name(['*.json'])->files();
$this->googleTranslate = new GoogleTranslate();

foreach ($finder as $file) {
$locale = $file->getFilenameWithoutExtension();

if (! in_array($locale, $locales)) {
continue;
}

$this->info('loading locale: '.$locale);
$jsonString = $file->getContents();
$strings = json_decode($jsonString, true);

$this->translateStrings($locale, $strings);
}
}

private function translateStrings(string $locale, array $strings)
{
foreach ($strings as $index => $value) {
if ($value === '') {
$this->googleTranslate->setTarget($locale);
$translated = $this->googleTranslate->translate($index);
$this->info('translating: `'.$index.'` to `'.$translated.'`');

// we store the translated string in the array
$strings[$index] = $translated;
}
}

// now we need to save the array back to the file
Storage::disk('lang')->put($locale.'.json', json_encode($strings, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}
}
1 change: 1 addition & 0 deletions composer.json
Expand Up @@ -37,6 +37,7 @@
"socialiteproviders/linkedin": "^4.2",
"socialiteproviders/microsoft-azure": "^5.1",
"socialiteproviders/twitter": "^4.1",
"stichoza/google-translate-php": "^5.1",
"tightenco/ziggy": "1.5.2",
"uploadcare/uploadcare-php": "^3.2"
},
Expand Down
97 changes: 87 additions & 10 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions config/filesystems.php
Expand Up @@ -35,6 +35,11 @@
'root' => storage_path('app'),
],

'lang' => [
'driver' => 'local',
'root' => lang_path(),
],

'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
Expand Down

0 comments on commit a91f3cb

Please sign in to comment.