TranslatorProvider::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Nette extension for bckp/translator
7
 * (c) Radovan Kepák
8
 *
9
 * For the full copyright and license information, please view the file license.md that was distributed with this source code.
10
 *
11
 * @author Radovan Kepak <[email protected]>
12
 *  --------------------------------------------------------------------------
13
 */
14
15
namespace Bckp\Translator\Nette;
16
17
use Bckp\Translator\CatalogueBuilder;
18
use Bckp\Translator\Exceptions\TranslatorException;
19
use Bckp\Translator\Interfaces\Diagnostics;
20
use Bckp\Translator\Translator;
21
use Tracy\Bar;
22
23
use function array_key_exists;
24
25
final class TranslatorProvider
26
{
27
	/**
28
	 * @var array<string, CatalogueBuilder>
29
	 */
30
	private array $builder = [];
31
32
	/**
33
	 * @var array<string, Translator>
34
	 */
35
	private array $translator = [];
36
37
	/** @api */
38
	public function __construct(
39
		private readonly ?Diagnostics $diagnostics = null,
40
	) {}
41
42
	/**
43
	 * @api
44
	 */
45
	public function addCatalogueBuilder(CatalogueBuilder $builder): void
46
	{
47
		$this->builder[$builder->getLocale()] = $builder;
48
	}
49
50
	/**
51
	 * @api
52
	 * @throws TranslatorException
53
	 */
54
	public function getTranslator(string $locale): Translator
55
	{
56
		$locale = $this->normalizeLocale($locale);
57
58
		if (!array_key_exists($locale, $this->builder)) {
59
			throw new TranslatorException("Locale {$locale} not found, available locales: " . implode(', ', array_keys($this->builder)));
60
		}
61
62
		return $this->translator[$locale] ??= new Translator($this->builder[$locale]->compile(), $this->diagnostics);
63
	}
64
65
	private function normalizeLocale(string $locale): string
66
	{
67
		return strtolower($locale);
68
	}
69
}
70