Passed
Push — master ( aa4bd1...609353 )
by
unknown
02:27
created

dispatchMissingTranslationCategoryEvent()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 2
nop 1
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Translator;
6
7
use Psr\EventDispatcher\EventDispatcherInterface;
8
use RuntimeException;
9
use Yiisoft\I18n\Locale;
10
use Yiisoft\Translator\Event\MissingTranslationCategoryEvent;
11
use Yiisoft\Translator\Event\MissingTranslationEvent;
12
13
/**
14
 * Translator translates a message into the specified language.
15
 */
16
final class Translator implements TranslatorInterface
17
{
18
    private string $defaultCategory = 'app';
19
    private string $locale;
20
    private ?string $fallbackLocale;
21
    private ?EventDispatcherInterface $eventDispatcher;
22
23
    /**
24
     * @var CategorySource[][] Array of category message sources indexed by category names.
25
     */
26
    private array $categorySources = [];
27
28
    private ?SimpleMessageFormatter $simpleMessageFormatter = null;
29
30
    /**
31
     * @psalm-var array<string,true>
32
     */
33
    private array $dispatchedMissingTranslationCategoryEvents = [];
34
35
    /**
36
     * @param string $locale Default locale to use if locale is not specified explicitly.
37
     * @param string|null $fallbackLocale Locale to use if message for the locale specified was not found. Null for none.
38
     * @param EventDispatcherInterface|null $eventDispatcher Event dispatcher for translation events. Null for none.
39
     */
40 55
    public function __construct(
41
        string $locale = 'en_US',
42
        ?string $fallbackLocale = null,
43
        ?EventDispatcherInterface $eventDispatcher = null
44
    ) {
45 55
        $this->locale = $locale;
46 55
        $this->fallbackLocale = $fallbackLocale;
47 55
        $this->eventDispatcher = $eventDispatcher;
48
    }
49
50 52
    public function addCategorySource(CategorySource $category): void
51
    {
52 52
        if (isset($this->categorySources[$category->getName()])) {
53 14
            $this->categorySources[$category->getName()][] = $category;
54
        } else {
55 52
            $this->categorySources[$category->getName()] = [$category];
56
        }
57
    }
58
59 15
    public function addCategorySources(array $categories): void
60
    {
61 15
        foreach ($categories as $category) {
62 15
            $this->addCategorySource($category);
63
        }
64
    }
65
66 3
    public function setLocale(string $locale): void
67
    {
68 3
        $this->locale = $locale;
69
    }
70
71 4
    public function getLocale(): string
72
    {
73 4
        return $this->locale;
74
    }
75
76 52
    public function translate(
77
        string $id,
78
        array $parameters = [],
79
        string $category = null,
80
        string $locale = null
81
    ): string {
82 52
        $locale = $locale ?? $this->locale;
83
84 52
        $category = $category ?? $this->defaultCategory;
85
86 52
        if (empty($this->categorySources[$category])) {
87 3
            $this->dispatchMissingTranslationCategoryEvent($category);
88 3
            return $this->getSimpleMessageFormatter()->format($id, $parameters);
89
        }
90
91 49
        return $this->translateUsingCategorySources($id, $parameters, $category, $locale);
92
    }
93
94
    /**
95
     * @psalm-immutable
96
     */
97 2
    public function withCategory(string $category): self
98
    {
99 2
        if (!isset($this->categorySources[$category])) {
100 1
            throw new RuntimeException('Category with name "' . $category . '" does not exist.');
101
        }
102
103 1
        $new = clone $this;
104 1
        $new->defaultCategory = $category;
105 1
        return $new;
106
    }
107
108 1
    public function withLocale(string $locale): self
109
    {
110 1
        $new = clone $this;
111 1
        $new->setLocale($locale);
112 1
        return $new;
113
    }
114
115 49
    private function translateUsingCategorySources(
116
        string $id,
117
        array $parameters,
118
        string $category,
119
        string $locale
120
    ): string {
121 49
        $sourceCategory = end($this->categorySources[$category]);
122
        do {
123 49
            $message = $sourceCategory->getMessage($id, $locale, $parameters);
124
125 49
            if ($message !== null) {
126 36
                return $sourceCategory->format($message, $parameters, $locale);
127
            }
128
129 31
            if ($this->eventDispatcher !== null) {
130 12
                $this->eventDispatcher->dispatch(new MissingTranslationEvent($sourceCategory->getName(), $locale, $id));
131
            }
132 31
        } while (($sourceCategory = prev($this->categorySources[$category])) !== false);
133
134 26
        $localeObject = new Locale($locale);
135 26
        $fallback = $localeObject->fallbackLocale();
136
137 26
        if ($fallback->asString() !== $localeObject->asString()) {
138 14
            return $this->translateUsingCategorySources($id, $parameters, $category, $fallback->asString());
139
        }
140
141 19
        if (!empty($this->fallbackLocale)) {
142 10
            $fallbackLocaleObject = (new Locale($this->fallbackLocale))->fallbackLocale();
143 10
            if ($fallbackLocaleObject->asString() !== $localeObject->asString()) {
144 9
                return $this->translateUsingCategorySources($id, $parameters, $category, $fallbackLocaleObject->asString());
145
            }
146
        }
147
148 13
        $categorySource = end($this->categorySources[$category]);
149 13
        return $categorySource->format($id, $parameters, $locale);
150
    }
151
152 3
    private function dispatchMissingTranslationCategoryEvent(string $category): void
153
    {
154
        if (
155 3
            $this->eventDispatcher !== null
156 3
            && !isset($this->dispatchedMissingTranslationCategoryEvents[$category])
157
        ) {
158 2
            $this->dispatchedMissingTranslationCategoryEvents[$category] = true;
159 2
            $this->eventDispatcher->dispatch(new MissingTranslationCategoryEvent($category));
160
        }
161
    }
162
163 3
    private function getSimpleMessageFormatter(): SimpleMessageFormatter
164
    {
165 3
        if ($this->simpleMessageFormatter === null) {
166 3
            $this->simpleMessageFormatter = new SimpleMessageFormatter();
167
        }
168 3
        return $this->simpleMessageFormatter;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->simpleMessageFormatter could return the type null which is incompatible with the type-hinted return Yiisoft\Translator\SimpleMessageFormatter. Consider adding an additional type-check to rule them out.
Loading history...
169
    }
170
}
171