|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Tempest\Internationalization; |
| 6 | + |
| 7 | +use Tempest\Discovery\DiscoversPath; |
| 8 | +use Tempest\Discovery\Discovery; |
| 9 | +use Tempest\Discovery\DiscoveryLocation; |
| 10 | +use Tempest\Discovery\IsDiscovery; |
| 11 | +use Tempest\Reflection\ClassReflector; |
| 12 | +use Tempest\Support\Language\Locale; |
| 13 | + |
| 14 | +use function Tempest\Support\arr; |
| 15 | +use function Tempest\Support\str; |
| 16 | +use function Tempest\Support\Str\ends_with; |
| 17 | + |
| 18 | +final class TranslationMessageDiscovery implements Discovery, DiscoversPath |
| 19 | +{ |
| 20 | + use IsDiscovery; |
| 21 | + |
| 22 | + public function __construct( |
| 23 | + private readonly InternationalizationConfig $config, |
| 24 | + ) {} |
| 25 | + |
| 26 | + public function discover(DiscoveryLocation $location, ClassReflector $class): void |
| 27 | + { |
| 28 | + return; |
| 29 | + } |
| 30 | + |
| 31 | + public function discoverPath(DiscoveryLocation $location, string $path): void |
| 32 | + { |
| 33 | + if (! ends_with($path, '.json')) { |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + if (! $this->isLocale($locale = str($path)->beforeLast('.')->afterLast('.')->toString())) { |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + if (! is_file($path)) { |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + $this->discoveryItems->add($location, [$path, $locale]); |
| 46 | + } |
| 47 | + |
| 48 | + public function apply(): void |
| 49 | + { |
| 50 | + foreach ($this->discoveryItems as [$path, $locale]) { |
| 51 | + $this->config->addTranslationMessageFile(Locale::from($locale), $path); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + private function isLocale(string $candidate): bool |
| 56 | + { |
| 57 | + $locale = arr(Locale::cases()) |
| 58 | + ->first(function (Locale $locale) use ($candidate) { |
| 59 | + if (strtolower($locale->value) === strtolower($candidate)) { |
| 60 | + return true; |
| 61 | + } |
| 62 | + |
| 63 | + return strtolower($locale->getLanguage()) === strtolower($candidate); |
| 64 | + }); |
| 65 | + |
| 66 | + return ! is_null($locale); |
| 67 | + } |
| 68 | +} |
0 commit comments