From 2a9cca8e37485792407391ec86d0b8d966b4c595 Mon Sep 17 00:00:00 2001 From: rubens <10297656+rubensrocha@users.noreply.github.com> Date: Wed, 28 May 2025 22:09:21 -0300 Subject: [PATCH] Changed: Code optimizations --- src/Console/CleanCommand.php | 4 +- src/Console/ExportCommand.php | 12 +-- src/Console/FindCommand.php | 4 +- src/Console/ImportCommand.php | 6 +- src/Console/ResetCommand.php | 4 +- src/Controller.php | 14 ++-- src/Manager.php | 118 ++++++++++++++++++----------- src/ManagerServiceProvider.php | 19 +++-- src/TranslationServiceProvider.php | 2 +- src/Translator.php | 17 +++-- src/routes.php | 4 +- 11 files changed, 115 insertions(+), 89 deletions(-) diff --git a/src/Console/CleanCommand.php b/src/Console/CleanCommand.php index c23c5c56..8f601766 100644 --- a/src/Console/CleanCommand.php +++ b/src/Console/CleanCommand.php @@ -21,7 +21,7 @@ class CleanCommand extends Command */ protected $description = 'Clean empty translations'; - /** @var \Barryvdh\TranslationManager\Manager */ + /** @var Manager */ protected $manager; public function __construct(Manager $manager) @@ -33,7 +33,7 @@ public function __construct(Manager $manager) /** * Execute the console command. */ - public function handle() + public function handle(): void { $this->manager->cleanTranslations(); $this->info('Done cleaning translations'); diff --git a/src/Console/ExportCommand.php b/src/Console/ExportCommand.php index ee0e63db..b4ad4365 100644 --- a/src/Console/ExportCommand.php +++ b/src/Console/ExportCommand.php @@ -23,7 +23,7 @@ class ExportCommand extends Command */ protected $description = 'Export translations to PHP files'; - /** @var \Barryvdh\TranslationManager\Manager */ + /** @var Manager */ protected $manager; public function __construct(Manager $manager) @@ -35,7 +35,7 @@ public function __construct(Manager $manager) /** * Execute the console command. */ - public function handle() + public function handle(): void { $group = $this->option('all') ? '*' : $this->argument('group'); $json = $this->option('json'); @@ -52,7 +52,7 @@ public function handle() return; } - if ( $group == '*' ) { + if ( $group === '*' ) { $this->manager->exportAllTranslations(); } else { @@ -60,7 +60,7 @@ public function handle() } if (!is_null($group)) { - $this->info('Done writing language files for '.(($group == '*') ? 'ALL groups' : $group.' group')); + $this->info('Done writing language files for '.(($group === '*') ? 'ALL groups' : $group.' group')); } elseif ($json) { $this->info('Done writing JSON language files for translation strings'); } @@ -71,7 +71,7 @@ public function handle() * * @return array */ - protected function getArguments() + protected function getArguments(): array { return [ ['group', InputArgument::OPTIONAL, 'The group to export (--all for all).'], @@ -83,7 +83,7 @@ protected function getArguments() * * @return array */ - protected function getOptions() + protected function getOptions(): array { return [ ['json', 'J', InputOption::VALUE_NONE, 'Export anonymous strings to JSON'], diff --git a/src/Console/FindCommand.php b/src/Console/FindCommand.php index 1c49d421..b6170780 100644 --- a/src/Console/FindCommand.php +++ b/src/Console/FindCommand.php @@ -21,7 +21,7 @@ class FindCommand extends Command */ protected $description = 'Find translations in php/twig files'; - /** @var \Barryvdh\TranslationManager\Manager */ + /** @var Manager */ protected $manager; public function __construct(Manager $manager) @@ -33,7 +33,7 @@ public function __construct(Manager $manager) /** * Execute the console command. */ - public function handle() + public function handle(): void { $counter = $this->manager->findTranslations(null); $this->info('Done importing, processed '.$counter.' items!'); diff --git a/src/Console/ImportCommand.php b/src/Console/ImportCommand.php index d2e4fc05..c1b9e952 100644 --- a/src/Console/ImportCommand.php +++ b/src/Console/ImportCommand.php @@ -22,7 +22,7 @@ class ImportCommand extends Command */ protected $description = 'Import translations from the PHP sources'; - /** @var \Barryvdh\TranslationManager\Manager */ + /** @var Manager */ protected $manager; public function __construct(Manager $manager) @@ -34,7 +34,7 @@ public function __construct(Manager $manager) /** * Execute the console command. */ - public function handle() + public function handle(): void { $replace = $this->option('replace'); $counter = $this->manager->importTranslations($replace); @@ -46,7 +46,7 @@ public function handle() * * @return array */ - protected function getOptions() + protected function getOptions(): array { return [ ['replace', 'R', InputOption::VALUE_NONE, 'Replace existing keys'], diff --git a/src/Console/ResetCommand.php b/src/Console/ResetCommand.php index fbc76e3c..03012141 100644 --- a/src/Console/ResetCommand.php +++ b/src/Console/ResetCommand.php @@ -21,7 +21,7 @@ class ResetCommand extends Command */ protected $description = 'Delete all translations from the database'; - /** @var \Barryvdh\TranslationManager\Manager */ + /** @var Manager */ protected $manager; public function __construct(Manager $manager) @@ -33,7 +33,7 @@ public function __construct(Manager $manager) /** * Execute the console command. */ - public function handle() + public function handle(): void { $this->manager->truncateTranslations(); $this->info('All translations are deleted'); diff --git a/src/Controller.php b/src/Controller.php index 31ab43c0..993ffe8f 100644 --- a/src/Controller.php +++ b/src/Controller.php @@ -56,7 +56,7 @@ public function getView($group = null) return $this->getIndex($group); } - protected function loadLocales() + protected function loadLocales(): array { //Set the default locale as the first one. $locales = Translation::groupBy('locale') @@ -111,7 +111,7 @@ public function postDelete($group, $key) } } - public function postImport(Request $request) + public function postImport(Request $request): array { $replace = $request->get('replace', false); $counter = $this->manager->importTranslations($replace); @@ -119,14 +119,14 @@ public function postImport(Request $request) return ['status' => 'ok', 'counter' => $counter]; } - public function postFind() + public function postFind(): array { $numFound = $this->manager->findTranslations(); return ['status' => 'ok', 'counter' => (int) $numFound]; } - public function postPublish($group = null) + public function postPublish($group = null): array { $json = false; @@ -146,10 +146,8 @@ public function postAddGroup(Request $request) { return redirect()->action('\Barryvdh\TranslationManager\Controller@getView',$group); } - else - { - return redirect()->back(); - } + + return redirect()->back(); } public function postAddLocale(Request $request) diff --git a/src/Manager.php b/src/Manager.php index b33530a3..255e8efd 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -2,6 +2,7 @@ namespace Barryvdh\TranslationManager; +use Illuminate\Contracts\Filesystem\FileNotFoundException; use Illuminate\Support\Arr; use Illuminate\Support\Str; use Symfony\Component\Finder\Finder; @@ -15,11 +16,11 @@ class Manager { const JSON_GROUP = '_json'; - /** @var \Illuminate\Contracts\Foundation\Application */ + /** @var Application */ protected $app; - /** @var \Illuminate\Filesystem\Filesystem */ + /** @var Filesystem */ protected $files; - /** @var \Illuminate\Contracts\Events\Dispatcher */ + /** @var Dispatcher */ protected $events; protected $config; @@ -30,6 +31,10 @@ class Manager protected $ignoreFilePath; + /** + * @throws FileNotFoundException + * @throws \JsonException + */ public function __construct(Application $app, Filesystem $files, Dispatcher $events) { $this->app = $app; @@ -41,22 +46,26 @@ public function __construct(Application $app, Filesystem $files, Dispatcher $eve $this->ignoreLocales = $this->getIgnoredLocales(); } - protected function getIgnoredLocales() + /** + * @throws FileNotFoundException + * @throws \JsonException + */ + protected function getIgnoredLocales(): array { if (! $this->files->exists($this->ignoreFilePath)) { return []; } - $result = json_decode($this->files->get($this->ignoreFilePath)); + $result = json_decode($this->files->get($this->ignoreFilePath), false, 512, JSON_THROW_ON_ERROR); return ($result && is_array($result)) ? $result : []; } - public function importTranslations($replace = false, $base = null, $import_group = false) + public function importTranslations($replace = false, $base = null, $import_group = false): int { $counter = 0; //allows for vendor lang files to be properly recorded through recursion. $vendor = true; - if ($base == null) { + if ($base === null) { $base = $this->app['path.lang']; $vendor = false; } @@ -64,8 +73,8 @@ public function importTranslations($replace = false, $base = null, $import_group foreach ($this->files->directories($base) as $langPath) { $locale = basename($langPath); - //import langfiles for each vendor - if ($locale == 'vendor') { + //import lang files for each vendor + if ($locale === 'vendor') { foreach ($this->files->directories($langPath) as $vendor) { $counter += $this->importTranslations($replace, $vendor); } @@ -76,10 +85,8 @@ public function importTranslations($replace = false, $base = null, $import_group foreach ($this->files->allfiles($langPath) as $file) { $info = pathinfo($file); $group = $info['filename']; - if ($import_group) { - if ($import_group !== $group) { - continue; - } + if ($import_group && $import_group !== $group) { + continue; } if (in_array($group, $this->config['exclude_groups'])) { @@ -128,7 +135,7 @@ public function importTranslations($replace = false, $base = null, $import_group return $counter; } - public function importTranslation($key, $value, $locale, $group, $replace = false) + public function importTranslation($key, $value, $locale, $group, $replace = false): bool { // process only string values @@ -142,7 +149,7 @@ public function importTranslation($key, $value, $locale, $group, $replace = fals 'key' => $key, ]); - // Check if the database is different then the files + // Check if the database is different than the files $newStatus = $translation->value === $value ? Translation::STATUS_SAVED : Translation::STATUS_CHANGED; if ($newStatus !== (int) $translation->status) { $translation->status = $newStatus; @@ -158,7 +165,7 @@ public function importTranslation($key, $value, $locale, $group, $replace = fals return true; } - public function findTranslations($path = null) + public function findTranslations($path = null): int { $path = $path ?: base_path(); $groupKeys = []; @@ -166,19 +173,19 @@ public function findTranslations($path = null) $functions = $this->config['trans_functions']; $groupPattern = // See https://regex101.com/r/WEJqdL/6 - "[^\w|>]" . // Must not have an alphanum or _ or > before real method + "[^\w|>]" . // Must not have an alphanumeric or _ or > before a real method '(' . implode('|', $functions) . ')' . // Must start with one of the functions "\(" . // Match opening parenthesis "[\'\"]" . // Match " or ' '(' . // Start a new group to match: - '[\/a-zA-Z0-9_-]+' . // Must start with group + '[\/a-zA-Z0-9_-]+' . // Must start with a group "([.](?! )[^\1)]+)+" . // Be followed by one or more items/keys ')' . // Close group "[\'\"]" . // Closing quote "[\),]"; // Close parentheses or new parameter $stringPattern = - "[^\w]". // Must not have an alphanum before real method + "[^\w]". // Must not have an alphanumeric before a real method '('.implode('|', $functions).')'. // Must start with one of the functions "\(\s*". // Match opening parenthesis "(?P['\"])". // Match " or ' and store in {quote} @@ -239,7 +246,7 @@ public function findTranslations($path = null) return count($groupKeys + $stringKeys); } - public function missingKey($namespace, $group, $key) + public function missingKey($namespace, $group, $key): void { if (! in_array($group, $this->config['exclude_groups'])) { Translation::firstOrCreate([ @@ -250,7 +257,10 @@ public function missingKey($namespace, $group, $key) } } - public function exportTranslations($group = null, $json = false) + /** + * @throws \JsonException + */ + public function exportTranslations($group = null, $json = false): ?array { $group = basename($group); $basePath = $this->app['path.lang']; @@ -258,12 +268,12 @@ public function exportTranslations($group = null, $json = false) if (! is_null($group) && ! $json) { if (! in_array($group, $this->config['exclude_groups'])) { $vendor = false; - if ($group == '*') { + if ($group === '*') { return $this->exportAllTranslations(); - } else { - if (Str::startsWith($group, 'vendor')) { - $vendor = true; - } + } + + if (Str::startsWith($group, 'vendor')) { + $vendor = true; } $tree = $this->makeTree(Translation::ofTranslatedGroup($group) @@ -286,18 +296,18 @@ public function exportTranslations($group = null, $json = false) $subfolder_level = ''; foreach ($subfolders as $subfolder) { - $subfolder_level = $subfolder_level.$subfolder.DIRECTORY_SEPARATOR; + $subfolder_level .= $subfolder . DIRECTORY_SEPARATOR; $temp_path = rtrim($path.DIRECTORY_SEPARATOR.$subfolder_level, DIRECTORY_SEPARATOR); - if (! is_dir($temp_path)) { - mkdir($temp_path, 0777, true); + if (!is_dir($temp_path) && !mkdir($temp_path, 0777, true) && !is_dir($temp_path)) { + throw new \RuntimeException(sprintf('Directory "%s" was not created', $temp_path)); } } if ($vendor) { - $path = $path.DIRECTORY_SEPARATOR.'messages.php'; + $path .= DIRECTORY_SEPARATOR . 'messages.php'; } else { - $path = $path.DIRECTORY_SEPARATOR.$locale.DIRECTORY_SEPARATOR.$group.'.php'; + $path .= DIRECTORY_SEPARATOR . $locale . DIRECTORY_SEPARATOR . $group . '.php'; } $output = "app['path.lang'].'/'.$locale.'.json'; - $output = json_encode($translations, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE); + $output = json_encode($translations, JSON_THROW_ON_ERROR | \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE); $this->files->put($path, $output); } } @@ -328,12 +338,15 @@ public function exportTranslations($group = null, $json = false) $this->events->dispatch(new TranslationsExportedEvent()); } - public function exportAllTranslations() + /** + * @throws \JsonException + */ + public function exportAllTranslations(): array|null { $groups = Translation::whereNotNull('value')->selectDistinctGroup()->get('group'); foreach ($groups as $group) { - if ($group->group == self::JSON_GROUP) { + if ($group->group === self::JSON_GROUP) { $this->exportTranslations(null, true); } else { $this->exportTranslations($group->group); @@ -343,7 +356,7 @@ public function exportAllTranslations() $this->events->dispatch(new TranslationsExportedEvent()); } - protected function makeTree($translations, $json = false) + protected function makeTree($translations, $json = false): array { $array = []; foreach ($translations as $translation) { @@ -370,23 +383,23 @@ public function jsonSet(&$array, $key, $value) return $array; } - public function cleanTranslations() + public function cleanTranslations(): void { Translation::whereNull('value')->delete(); } - public function truncateTranslations() + public function truncateTranslations(): void { Translation::truncate(); } - public function getLocales() + public function getLocales(): array { if (empty($this->locales)) { $locales = array_merge([config('app.locale')], Translation::groupBy('locale')->pluck('locale')->toArray()); foreach ($this->files->directories($this->app->langPath()) as $localeDir) { - if (($name = $this->files->name($localeDir)) != 'vendor') { + if (($name = $this->files->name($localeDir)) !== 'vendor') { $locales[] = $name; } } @@ -398,7 +411,11 @@ public function getLocales() return array_diff($this->locales, $this->ignoreLocales); } - public function addLocale($locale) + /** + * @throws FileNotFoundException + * @throws \JsonException + */ + public function addLocale($locale): bool { $localeDir = $this->app->langPath().'/'.basename($locale); @@ -413,12 +430,19 @@ public function addLocale($locale) return true; } - protected function saveIgnoredLocales() + /** + * @throws \JsonException + */ + protected function saveIgnoredLocales(): bool|int { - return $this->files->put($this->ignoreFilePath, json_encode($this->ignoreLocales)); + return $this->files->put($this->ignoreFilePath, json_encode($this->ignoreLocales, JSON_THROW_ON_ERROR)); } - public function removeLocale($locale) + /** + * @throws FileNotFoundException + * @throws \JsonException + */ + public function removeLocale($locale): bool { if (! $locale) { return false; @@ -428,14 +452,16 @@ public function removeLocale($locale) $this->ignoreLocales = $this->getIgnoredLocales(); Translation::where('locale', $locale)->delete(); + + return true; } public function getConfig($key = null) { - if ($key == null) { + if ($key === null) { return $this->config; - } else { - return $this->config[$key]; } + + return $this->config[$key]; } } diff --git a/src/ManagerServiceProvider.php b/src/ManagerServiceProvider.php index daef4bd4..99f761df 100644 --- a/src/ManagerServiceProvider.php +++ b/src/ManagerServiceProvider.php @@ -1,7 +1,7 @@ mergeConfigFrom($configPath, 'translation-manager'); $this->publishes([$configPath => config_path('translation-manager.php')], 'config'); $this->app->singleton('translation-manager', function ($app) { - $manager = $app->make('Barryvdh\TranslationManager\Manager'); - return $manager; + return $app->make(Manager::class); }); $this->app->singleton('command.translation-manager.reset', function ($app) { @@ -59,8 +58,8 @@ public function register() * * @return void */ - public function boot() - { + public function boot(): void + { $viewPath = __DIR__.'/../resources/views'; $this->loadViewsFrom($viewPath, 'translation-manager'); $this->publishes([ @@ -80,8 +79,8 @@ public function boot() * * @return array */ - public function provides() - { + public function provides(): array + { return array('translation-manager', 'command.translation-manager.reset', 'command.translation-manager.import', diff --git a/src/TranslationServiceProvider.php b/src/TranslationServiceProvider.php index dd3ccc8e..5b8292c4 100644 --- a/src/TranslationServiceProvider.php +++ b/src/TranslationServiceProvider.php @@ -10,7 +10,7 @@ class TranslationServiceProvider extends BaseTranslationServiceProvider { * * @return void */ - public function register() + public function register(): void { $this->registerLoader(); diff --git a/src/Translator.php b/src/Translator.php index 28ed72f6..a2404e56 100644 --- a/src/Translator.php +++ b/src/Translator.php @@ -11,32 +11,33 @@ class Translator extends LaravelTranslator { /** * Get the translation for the given key. * - * @param string $key - * @param array $replace - * @param string $locale + * @param string $key + * @param array $replace + * @param null $locale + * @param bool $fallback * @return string */ - public function get($key, array $replace = array(), $locale = null, $fallback = true) + public function get($key, array $replace = array(), $locale = null, $fallback = true): string { - // Get without fallback + // Get without a fallback $result = parent::get($key, $replace, $locale, false); if($result === $key){ $this->notifyMissingKey($key); // Reget with fallback $result = parent::get($key, $replace, $locale, $fallback); - + } return $result; } - public function setTranslationManager(Manager $manager) + public function setTranslationManager(Manager $manager): void { $this->manager = $manager; } - protected function notifyMissingKey($key) + protected function notifyMissingKey($key): void { list($namespace, $group, $item) = $this->parseKey($key); if($this->manager && $namespace === '*' && $group && $item ){ diff --git a/src/routes.php b/src/routes.php index fefb399d..38bf8611 100644 --- a/src/routes.php +++ b/src/routes.php @@ -2,8 +2,10 @@ declare(strict_types=1); +use Illuminate\Support\Facades\Route; + $config = array_merge(config('translation-manager.route'), ['namespace' => 'Barryvdh\TranslationManager']); -Route::group($config, function($router) +Route::group($config, static function($router) { $router->get('view/{groupKey?}', 'Controller@getView')->where('groupKey', '.*'); $router->get('/{groupKey?}', 'Controller@getIndex')->where('groupKey', '.*');