Total Complexity | 4 |
Total Lines | 51 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | <?php |
||
6 | final class Translator |
||
7 | { |
||
8 | private static TranslatorInterface $translator; |
||
9 | |||
10 | public static function setDefault(TranslatorInterface|callable $translator, bool $compose = true): void |
||
11 | { |
||
12 | if ($translator instanceof TranslatorInterface) { |
||
13 | self::$translator = $translator; |
||
14 | } else { |
||
15 | self::$translator = new class($translator) implements TranslatorInterface { |
||
16 | private $callback; |
||
17 | |||
18 | public function __construct(callable $callback) |
||
19 | { |
||
20 | $this->callback = $callback; |
||
21 | } |
||
22 | |||
23 | public function translate(string $message, ...$args): ?string |
||
24 | { |
||
25 | return call_user_func_array($this->callback, [$message, ...$args]); |
||
26 | } |
||
27 | }; |
||
28 | } |
||
29 | |||
30 | if ($compose) { |
||
31 | self::$translator = new CompositeTranslator(self::$translator, self::createDefault()); |
||
32 | } |
||
33 | } |
||
34 | |||
35 | public static function getDefault(): TranslatorInterface |
||
38 | } |
||
39 | |||
40 | private static function createDefault(): TranslatorInterface |
||
41 | { |
||
42 | return new class implements TranslatorInterface { |
||
43 | public function translate(string $message, ...$args): ?string |
||
44 | { |
||
45 | return sprintf($message, ...$args); |
||
46 | } |
||
47 | }; |
||
48 | } |
||
49 | |||
50 | public static function translate(string $message, ...$args): string |
||
51 | { |
||
52 | return self::getDefault()->translate($message, ...$args) ?? $message; |
||
53 | } |
||
54 | |||
55 | private function __construct() |
||
57 | } |
||
58 | } |
||
59 |