Translation.php
46 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace AC\Asset\Script\Localize; |
| 6 | |
| 7 | use InvalidArgumentException; |
| 8 | |
| 9 | final class Translation |
| 10 | { |
| 11 | |
| 12 | private array $translations; |
| 13 | |
| 14 | public function __construct(array $translations) |
| 15 | { |
| 16 | $this->translations = $translations; |
| 17 | } |
| 18 | |
| 19 | public static function create(array $translations): self |
| 20 | { |
| 21 | return new self($translations); |
| 22 | } |
| 23 | |
| 24 | public function with_translation(array $translations): self |
| 25 | { |
| 26 | return self::create(array_merge($this->translations, $translations)); |
| 27 | } |
| 28 | |
| 29 | public function get_translation(?string $component = null): array |
| 30 | { |
| 31 | $translations = $this->translations; |
| 32 | |
| 33 | if ($component) { |
| 34 | if ( ! isset($translations[$component])) { |
| 35 | throw new InvalidArgumentException(sprintf('Undefined component %s for translation.', $component)); |
| 36 | } |
| 37 | |
| 38 | $translations = [ |
| 39 | $component => $translations[$component], |
| 40 | ]; |
| 41 | } |
| 42 | |
| 43 | return $translations; |
| 44 | } |
| 45 | |
| 46 | } |