-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
MonicaLocalize.php
81 lines (66 loc) · 2.31 KB
/
MonicaLocalize.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
namespace App\Console\Commands\Local;
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.
*
* @var string
*/
protected $signature = 'monica:localize';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate locale files for Monica.';
/**
* Execute the console command.
*/
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));
}
}