ldc-boutique-cnc-sable/app/Providers/TranslationServiceProvider.php
2026-10-27 09:58:12 +01:00

104 lines
3.2 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Providers;
use App\Lib\Helpers\ToolboxHelper;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Illuminate\Support\ServiceProvider;
use Symfony\Component\Finder\SplFileInfo;
class TranslationServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot(): void
{
if ($this->app->runningInConsole() && ! $this->app->runningUnitTests()) {
return;
}
foreach ($this->collectLocalesStrings() as $locale) {
// * Suported locales.
Cache::rememberForever(sprintf('translations.%s', $locale), function () use ($locale) {
$phpTransFallback = $this->phpTranslations(config()->string('app.fallback_locale'));
$phpTransLocale = $this->phpTranslations($locale);
$jsonTransFallback = $this->jsonTranslations(config()->string('app.fallback_locale'));
$jsonTransLocale = $this->jsonTranslations($locale);
return [
'php' => ToolboxHelper::arrayMergeRecursiveDistinct(
$phpTransFallback,
$phpTransLocale,
),
'json' => ToolboxHelper::arrayMergeRecursiveDistinct(
$jsonTransFallback,
$jsonTransLocale,
),
];
});
} // End foreach.
}
/**
* Gather provided langs checking from files.
*
* @return \Illuminate\Support\Collection<array-key,string>
*/
private function collectLocalesStrings(): Collection
{
// * En dur dans ->keys array<int,string>.
/** @var array<int,string> */
$locales = config('app.locales', []);
$files = File::allFiles(base_path('lang/'));
return Collection::make($files)->flatMap(function (SplFileInfo $file) {
if ($file->getRelativePath() && ! str_starts_with($file->getRelativePath(), 'vendor')) {
return [$file->getRelativePath() => ''];
}
})->keys()->merge($locales);
}
/**
* Gather all php translations.
*
* @return array<string, string>
*/
private function phpTranslations(string $locale): array
{
$path = base_path("lang/$locale");
if (! File::exists($path) || ! File::isReadable($path)) {
return [];
}
$files = File::allFiles($path);
return Collection::make($files)->flatMap(function ($file) use ($locale) {
$translation = $file->getBasename('.php');
return [$translation => trans($translation, [], $locale)];
})->all();
}
/**
* Gather json translations.
*
* @return array<string,mixed>
*/
private function jsonTranslations(string $locale): array
{
$path = base_path("lang/$locale.json");
if (! File::exists($path) || ! File::isReadable($path)) {
return [];
}
return Arr::wrap(json_decode(File::get($path), true));
}
}