Passed
Push — master ( 0740d8...825309 )
by Saif Eddin
11:01
created

TranslatorFactory   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 85
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 13
eloc 31
dl 0
loc 85
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getTranslationConfig() 0 10 1
A __invoke() 0 19 4
A addResources() 0 15 4
A addLoaders() 0 8 4
1
<?php
2
/**
3
 * This File is Part of the Validus Translation package.
4
 *
5
 * @copyright (c) 2018 Validus <https://github.com/ValidusPHP/>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
declare(strict_types=1);
12
13
namespace Validus\Translation;
14
15
use InvalidArgumentException;
16
use Psr\Container\ContainerInterface;
17
use Symfony\Component\Translation\Formatter\MessageFormatter;
18
use Symfony\Component\Translation\Translator;
19
use Symfony\Component\Translation\TranslatorInterface;
20
use function array_merge;
21
use function is_string;
22
23
class TranslatorFactory
24
{
25
    /**
26
     * @param ContainerInterface $container
27
     *
28
     * @return TranslatorInterface
29
     */
30
    public function __invoke(ContainerInterface $container): TranslatorInterface
31
    {
32
        $config = $container->has('config') ? $container->get('config') : [];
33
        $debug = $config['debug'] ?? true;
34
35
        $config = $this->getTranslationConfig($config);
36
37
        $formatter = $container->has($config['formatter']) ? $container->get($config['formatter']) : new $config['formatter']();
38
39
        $cache = $debug ? null : $config['cache_dir'];
40
        $translator = new Translator($config['locale'], $formatter, $cache, $debug);
41
42
        $this->addLoaders($container, $translator, $config['loaders']);
43
        $this->addResources($translator, $config['resources']);
44
45
        $translator->setFallbackLocales($config['fallback']);
46
        $translator->setLocale($config['locale']);
47
48
        return $translator;
49
    }
50
51
    /**
52
     * Add resources to the given translator instance.
53
     *
54
     * @param Translator $translator
55
     * @param array      $resources
56
     */
57
    protected function addResources(Translator $translator, array $resources = []): void
58
    {
59
        foreach ($resources as $id => $resource) {
60
            if (!isset($resource['format'])) {
61
                throw new InvalidArgumentException("resource format is missing from resources configuration#{$id}.");
62
            }
63
64
            if (!isset($resource['resource'])) {
65
                throw new InvalidArgumentException("resource is missing from resources configuration#{$id}.");
66
            }
67
68
            $resource['locale'] = $resource['locale'] ?? $config['locale'] ?? 'en';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $config seems to never exist and therefore isset should always be false.
Loading history...
69
            $resource['domain'] = $resource['domain'] ?? 'messages';
70
71
            $translator->addResource($resource['format'], $resource['resource'], $resource['locale'], $resource['domain']);
72
        }
73
    }
74
75
    /**
76
     * Add loaders to the given translator instance.
77
     *
78
     * @param ContainerInterface $container
79
     * @param Translator         $translator
80
     * @param array              $loaders
81
     */
82
    protected function addLoaders(ContainerInterface $container, Translator $translator, array $loaders = []): void
83
    {
84
        foreach ($loaders as $format => $loader) {
85
            if (is_string($loader)) {
86
                $loader = $container->has($loader) ? $container->get($loader) : new $loader();
87
            }
88
89
            $translator->addLoader($format, $loader);
90
        }
91
    }
92
93
    /**
94
     * @param array $config
95
     *
96
     * @return array
97
     */
98
    protected function getTranslationConfig(array $config): array
99
    {
100
        return array_merge([
101
            'locale' => 'en',
102
            'cache_dir' => null,
103
            'fallback' => [],
104
            'formatter' => MessageFormatter::class,
105
            'loaders' => [],
106
            'resources' => [],
107
        ], $config['translation'] ?? []);
108
    }
109
}
110