ldc-gen-game-web/app/Providers/TranslationServiceProvider.php

75 lines
2 KiB
PHP
Raw Permalink Normal View History

2023-08-21 10:22:07 +02:00
<?php
2026-10-02 12:09:46 +02:00
declare(strict_types=1);
2023-08-21 10:22:07 +02:00
namespace App\Providers;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
2026-10-02 12:09:46 +02:00
use Illuminate\Support\Facades\File;
2023-08-21 10:22:07 +02:00
use Illuminate\Support\ServiceProvider;
use Symfony\Component\Finder\SplFileInfo;
class TranslationServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot(): void
{
foreach ($this->collectLocalesStrings() as $locale) {
2023-11-23 17:31:28 +01:00
// * Suported locales
2026-10-02 12:09:46 +02:00
Cache::rememberForever(sprintf('translations.%s', $locale), fn (): array => [
'php' => $this->phpTranslations($locale),
'json' => $this->jsonTranslations($locale),
]);
2023-08-21 10:22:07 +02:00
}
}
/**
* Gather provided langs checking from files
*
2026-10-02 12:09:46 +02:00
* @return Collection<int, string>
2023-08-21 10:22:07 +02:00
*/
private function collectLocalesStrings(): Collection
{
return collect(File::allFiles(resource_path('lang/')))->flatMap(function (SplFileInfo $file) {
2026-10-02 12:09:46 +02:00
if ($file->getRelativePath() && ! str_starts_with($file->getRelativePath(), 'vendor')) {
2023-08-21 10:22:07 +02:00
return [$file->getRelativePath() => ''];
}
})->keys();
}
/**
* Gather all php translations
*
* @return array<string, string>
*/
private function phpTranslations(string $locale): array
{
$path = resource_path("lang/$locale");
2026-10-02 12:09:46 +02:00
return collect(File::allFiles($path))->flatMap(function ($file) use ($locale): array {
2023-08-21 10:22:07 +02:00
$translation = $file->getBasename('.php');
2026-10-02 12:09:46 +02:00
2023-08-21 10:22:07 +02:00
return [$translation => trans($translation, [], $locale)];
})->all();
}
/**
* Gather json translations
*
* @return array<string, string>
*/
private function jsonTranslations(string $locale): array
{
$path = resource_path("lang/$locale.json");
if (is_string($path) && is_readable($path)) {
return json_decode(file_get_contents($path), true) ?? [];
}
return [];
}
}