Localization.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Facades\File;
  5. class Localization extends Command
  6. {
  7. protected $signature = 'localization:generate';
  8. protected $description = 'Generate JSON files for all available localizations';
  9. public function __construct()
  10. {
  11. parent::__construct();
  12. }
  13. public function handle()
  14. {
  15. $languages = $this->discoverLangs();
  16. foreach ($languages as $lang) {
  17. $this->info("Processing {$lang} translations...");
  18. $this->buildTranslations($lang);
  19. }
  20. $this->info('All language files have been processed successfully!');
  21. }
  22. protected function buildTranslations(string $lang)
  23. {
  24. $path = base_path("resources/lang/{$lang}");
  25. $keys = [];
  26. $kcount = 0;
  27. if (! File::isDirectory($path)) {
  28. $this->error("Directory not found: {$path}");
  29. return;
  30. }
  31. foreach (new \DirectoryIterator($path) as $io) {
  32. if ($io->isDot() || ! $io->isFile()) {
  33. continue;
  34. }
  35. $key = $io->getBasename('.php');
  36. try {
  37. $translations = __($key, [], $lang);
  38. $keys[$key] = [];
  39. foreach ($translations as $k => $str) {
  40. $keys[$key][$k] = $str;
  41. $kcount++;
  42. }
  43. ksort($keys[$key]);
  44. } catch (\Exception $e) {
  45. $this->warn("Failed to process {$lang}/{$key}.php: {$e->getMessage()}");
  46. }
  47. }
  48. $result = $this->prepareOutput($keys, $kcount);
  49. $this->saveTranslations($result, $lang);
  50. }
  51. protected function prepareOutput(array $keys, int $keyCount): array
  52. {
  53. $output = $keys;
  54. $hash = hash('sha256', json_encode($output));
  55. $output['_meta'] = [
  56. 'key_count' => $keyCount,
  57. 'generated' => now()->toAtomString(),
  58. 'hash_sha256' => $hash,
  59. ];
  60. ksort($output);
  61. return $output;
  62. }
  63. protected function saveTranslations(array $translations, string $lang)
  64. {
  65. $directory = public_path('_lang');
  66. if (! File::isDirectory($directory)) {
  67. File::makeDirectory($directory, 0755, true);
  68. }
  69. $filename = "{$directory}/{$lang}.json";
  70. $contents = json_encode($translations, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
  71. File::put($filename, $contents);
  72. $this->info("Generated {$lang}.json");
  73. }
  74. protected function discoverLangs(): array
  75. {
  76. $path = base_path('resources/lang');
  77. $languages = [];
  78. foreach (new \DirectoryIterator($path) as $io) {
  79. $name = $io->getFilename();
  80. if (! $io->isDot() && $io->isDir() && $name !== 'vendor') {
  81. $languages[] = $name;
  82. }
  83. }
  84. return $languages;
  85. }
  86. }