Skip to content

Instantly share code, notes, and snippets.

@innocenzi
Created January 27, 2022 18:41
Show Gist options
  • Save innocenzi/a9b3b7161a6ebe04d7c31946c7ab7fe7 to your computer and use it in GitHub Desktop.
Save innocenzi/a9b3b7161a6ebe04d7c31946c7ab7fe7 to your computer and use it in GitHub Desktop.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
/**
* Generates a JSON file with all translations.
*/
class GenerateI18n extends Command
{
protected $signature = 'i18n:generate';
protected $description = 'Generates i18n files.';
public function handle(): int
{
if ($success = $this->writeTranslations()) {
$this->info("Translations written to <comment>{$this->getTranslationFilePath()}</comment>.");
}
return $success ? 0 : 1;
}
/**
* Recursively loads translations in the given directory.
*/
protected function makeFolderFilesTree(string $directory): array
{
$tree = [];
if (! $files = scandir($directory)) {
return [];
}
foreach ($files as $fileName) {
if (Str::startsWith($fileName, '.')) {
continue;
}
$extension = '.' . Str::afterLast($fileName, '.');
$fileName = basename($fileName, $extension);
$tree[$fileName] = [];
if (is_dir($directory . '/' . $fileName)) {
$tree[$fileName] = $this->makeFolderFilesTree($directory . '/' . $fileName);
}
if (is_file($pathName = $directory . '/' . $fileName . $extension)) {
if ($extension === '.json') {
$existingTranslations = $tree[$fileName] ?? [];
$tree[$fileName] = array_merge(
$existingTranslations,
json_decode(File::get($pathName), true)
);
}
if ($extension === '.php') {
$tree[$fileName] = require($pathName);
}
}
}
return $tree;
}
/**
* Gets the translations as an array.
*/
protected function getTranslations(): array
{
return $this->makeFolderFilesTree(resource_path('lang'));
}
/**
* Gets the path to the translation file.
*/
protected function getTranslationFilePath(): string
{
return str_replace('/', \DIRECTORY_SEPARATOR, resource_path('scripts/i18n.json'));
}
/**
* Writes the translations to the file system.
*/
protected function writeTranslations(): bool
{
return (bool) File::put(
$this->getTranslationFilePath(),
preg_replace('/:(\w+)/', '{${1}}', json_encode($this->getTranslations()))
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment