-
-
Save abdumu/c123d4f9a3666cfdb1c8ec643ba7734f to your computer and use it in GitHub Desktop.
Get translatable strings (__, @lang) for Laravel folders
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Console\Commands; | |
use Illuminate\Console\Command; | |
use Illuminate\Support\Arr; | |
use Illuminate\Support\Collection; | |
use Illuminate\Support\Str; | |
use Illuminate\Support\Facades\File; | |
use SplFileInfo; | |
class ExtractTranslatableStringsCommand extends Command | |
{ | |
protected $signature = 'translatable:extract {--e|--export=en}'; | |
protected $description = 'Extract Translatable Strings'; | |
protected $allowedExtensions = ['.php', '.vue', '.js']; | |
protected $includedFolders = ['app', 'resources']; | |
protected $methods = [ | |
'__', '@lang' | |
]; | |
public function __construct() | |
{ | |
parent::__construct(); | |
} | |
public function handle() | |
{ | |
$regex = '/(?:' . implode('|', $this->methods) . ')\((?<quotation>["\'])(?<string>(?:\\\\\k<quotation>|.)*?)\k<quotation>[^\)]*\)/i'; | |
$results = Collection::make($this->includedFolders) | |
->map(function ($folder) { | |
return File::allFiles(trim($folder)); | |
}) | |
->flatten() | |
->filter(function (SplFileInfo $file) { | |
return Str::endsWith($file->getPathname(), $this->allowedExtensions); | |
}) | |
->map(function (SplFileInfo $file) use ($regex) { | |
preg_match_all($regex, file_get_contents($file->getRealPath()), $matches, PREG_SET_ORDER, 0); | |
return Arr::pluck($matches, 'string'); | |
}) | |
->flatten() | |
->unique() | |
->toArray(); | |
$results = json_encode( | |
array_combine($results, $results), | |
JSON_PRETTY_PRINT | |
); | |
$export = $this->option('export'); | |
$overwrite = true; | |
if (file_exists(resource_path('lang/' . $export . '.json'))) { | |
$overwrite = $this->ask('`lang/' . $export . '.json` already exists! Would you like to overwrite the file?'); | |
} | |
if($overwrite) { | |
file_put_contents(resource_path('lang/' . $export . '.json'), $results); | |
$this->info('Exporting to `lang/' . $export . '.json` is complete...'); | |
} else { | |
$this->info('Aborted!'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment