Test Failed
Pull Request — master (#35)
by Alexander
02:09
created

Translator::translateUsingCategorySources()   B

Complexity

Conditions 7
Paths 9

Size

Total Lines 35
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 35
ccs 16
cts 16
cp 1
rs 8.8333
cc 7
nc 9
nop 4
crap 7
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
use function array_key_exists;
13
14
/**
15
 * Translator translates a message into the specified language.
16
 */
17
class Translator implements TranslatorInterface
18
{
19
    private string $defaultCategory = 'app';
20
    private string $locale;
21
    private ?string $fallbackLocale;
22
    private ?EventDispatcherInterface $eventDispatcher;
23
    /**
24
     * @var CategorySource[][] Array of category message sources indexed by category names.
25
     */
26
    private array $categorySources = [];
27
28
    /**
29
     * @param string $locale Default locale to use if locale is not specified explicitly.
30
     * @param string|null $fallbackLocale Locale to use if message for the locale specified was not found. Null for none.
31 41
     * @param EventDispatcherInterface|null $eventDispatcher Event dispatcher for translation events. Null for none.
32
     */
33
    public function __construct(
34
        string $locale,
35
        ?string $fallbackLocale = null,
36 41
        ?EventDispatcherInterface $eventDispatcher = null
37 41
    ) {
38 41
        $this->locale = $locale;
39 41
        $this->fallbackLocale = $fallbackLocale;
40
        $this->eventDispatcher = $eventDispatcher;
41 39
    }
42
43 39
    public function addCategorySource(CategorySource $category): void
44 1
    {
45
        if (!array_key_exists($category->getName(), $this->categorySources)) {
46 39
            $this->categorySources[$category->getName()][] = $category;
47 39
        } else {
48
            $this->categorySources[$category->getName()] = [$category];
49
        }
50
    }
51
52 1
    /**
53
     * @param CategorySource[] $categories
54 1
     */
55 1
    public function addCategorySources(array $categories): void
56
    {
57 1
        foreach ($categories as $category) {
58
            $this->addCategorySource($category);
59 3
        }
60
    }
61 3
62 3
    public function setLocale(string $locale): void
63
    {
64 3
        $this->locale = $locale;
65
    }
66 3
67
    public function getLocale(): string
68
    {
69 38
        return $this->locale;
70
    }
71
72
    public function translate(
73
        string $id,
74
        array $parameters = [],
75 38
        string $category = null,
76
        string $locale = null
77 38
    ): string {
78
        $locale = $locale ?? $this->locale;
79 38
80 3
        $category = $category ?? $this->defaultCategory;
81 2
82
        if (empty($this->categorySources[$category])) {
83 3
            if ($this->eventDispatcher !== null) {
84
                $this->eventDispatcher->dispatch(new MissingTranslationCategoryEvent($category));
85
            }
86 35
            return $id;
87 35
        }
88
89 35
        return $this->translateUsingCategorySources($id, $parameters, $category, $locale);
90 18
    }
91 12
92
    private function translateUsingCategorySources(
93
        string $id,
94 18
        array $parameters,
95 18
        string $category,
96
        string $locale
97 18
    ): string {
98 11
        $sourceCategory = end($this->categorySources[$category]);
99
        do {
100
            $message = $sourceCategory->getMessage($id, $locale, $parameters);
101 12
102 3
            if ($message !== null) {
103 3
                return $sourceCategory->format($message, $parameters, $locale);
104 3
            }
105
106
            if ($this->eventDispatcher !== null) {
107
                $this->eventDispatcher->dispatch(new MissingTranslationEvent($sourceCategory->getName(), $locale, $id));
108 9
            }
109
        } while (($sourceCategory = prev($this->categorySources[$category])) !== false);
110
111 35
        $localeObject = new Locale($locale);
112
        $fallback = $localeObject->fallbackLocale();
113
114
        if ($fallback->asString() !== $localeObject->asString()) {
115
            return $this->translateUsingCategorySources($id, $parameters, $category, $fallback->asString());
116
        }
117 2
118
        if (!empty($this->fallbackLocale)) {
119 2
            $fallbackLocaleObject = (new Locale($this->fallbackLocale))->fallbackLocale();
120 1
            if ($fallbackLocaleObject->asString() !== $localeObject->asString()) {
121
                return $this->translateUsingCategorySources($id, $parameters, $category, $fallbackLocaleObject->asString());
122
            }
123 1
        }
124 1
125 1
        $categorySource = end($this->categorySources[$category]);
126
        return $categorySource->format($id, $parameters, $locale);
127
    }
128 1
129
    /**
130 1
     * @psalm-immutable
131 1
     */
132 1
    public function withCategory(string $category): self
133
    {
134
        if (!isset($this->categorySources[$category])) {
135
            throw new RuntimeException('Category with name "' . $category . '" does not exist.');
136
        }
137
138
        $new = clone $this;
139
        $new->defaultCategory = $category;
140
        return $new;
141
    }
142
143
    public function withLocale(string $locale): self
144
    {
145
        $new = clone $this;
146
        $new->setLocale($locale);
147
        return $new;
148
    }
149
}
150