Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
18 / 18 |
|
100.00% |
4 / 4 |
CRAP | |
100.00% |
1 / 1 |
| TranslationServiceProvider | |
100.00% |
18 / 18 |
|
100.00% |
4 / 4 |
8 | |
100.00% |
1 / 1 |
| boot | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
2 | |||
| collectLocalesStrings | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
| phpTranslations | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
1 | |||
| jsonTranslations | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
3 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Providers; |
| 4 | |
| 5 | use Illuminate\Support\Collection; |
| 6 | use Illuminate\Support\Facades\File; |
| 7 | use Illuminate\Support\Facades\Cache; |
| 8 | use Illuminate\Support\ServiceProvider; |
| 9 | |
| 10 | class TranslationServiceProvider extends ServiceProvider |
| 11 | { |
| 12 | /** |
| 13 | * Bootstrap the application services. |
| 14 | * |
| 15 | * @return void |
| 16 | */ |
| 17 | public function boot() |
| 18 | { |
| 19 | foreach ($this->collectLocalesStrings() as $locale) { |
| 20 | // * Suported locales |
| 21 | Cache::rememberForever(sprintf('translations.%s', $locale), function () use ($locale) { |
| 22 | $translations = [ |
| 23 | 'php' => $this->phpTranslations($locale), |
| 24 | 'json' => $this->jsonTranslations($locale), |
| 25 | ]; |
| 26 | return $translations; |
| 27 | }); |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | /** |
| 32 | * Gather provided langs checking from files |
| 33 | * |
| 34 | * @return Collection |
| 35 | */ |
| 36 | private function collectLocalesStrings(): Collection |
| 37 | { |
| 38 | return collect(File::allFiles(resource_path('lang/')))->flatMap(function ($file) { |
| 39 | if ($file->getRelativePath()) { |
| 40 | return [$file->getRelativePath() => '']; |
| 41 | } |
| 42 | })->keys(); |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * Gather all php translations |
| 47 | * |
| 48 | * @param string $locale |
| 49 | * @return array |
| 50 | */ |
| 51 | private function phpTranslations(string $locale): array |
| 52 | { |
| 53 | $path = resource_path("lang/$locale"); |
| 54 | |
| 55 | return collect(File::allFiles($path))->flatMap(function ($file) use ($locale) { |
| 56 | $translation = $file->getBasename('.php'); |
| 57 | return [$translation => trans($translation, [], $locale)]; |
| 58 | })->all(); |
| 59 | } |
| 60 | |
| 61 | /** |
| 62 | * Gather json translations |
| 63 | * |
| 64 | * @param string $locale |
| 65 | * @return array |
| 66 | */ |
| 67 | private function jsonTranslations(string $locale): array |
| 68 | { |
| 69 | $path = resource_path("lang/$locale.json"); |
| 70 | |
| 71 | if (is_string($path) && is_readable($path)) { |
| 72 | return json_decode(file_get_contents($path), true) ?? []; |
| 73 | } |
| 74 | |
| 75 | return []; |
| 76 | } |
| 77 | } |