Passed
Pull Request — master (#59)
by
unknown
12:31
created

Translator::setLocale()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Locastic\ApiPlatformTranslationBundle\Translation;
6
7
use Symfony\Component\HttpFoundation\RequestStack;
8
use Symfony\Contracts\Translation\TranslatorInterface;
9
10
/**
11
 * @package Locastic\ApiPlatformTranslationBundle\Translation
12
 */
13
class Translator implements TranslatorInterface
14
{
15
    public function __construct(
16
        private TranslatorInterface $translator,
17
        private RequestStack $requestStack,
18
        private string $defaultLocale
19
    ) {
20
    }
21
22
    /**
23
     * {@inheritdoc}
24
     */
25
    public function trans($id, array $parameters = [], string $domain = null, string $locale = null): string
26
    {
27
        if ($locale === null) {
28
            $locale = $this->loadCurrentLocale();
29
        }
30
31
        return $this->translator->trans($id, $parameters, $domain, $locale);
32
    }
33
34
    public function loadCurrentLocale(): string
35
    {
36
        $request = $this->requestStack->getCurrentRequest();
37
38
        if (!$request) {
39
            return $this->defaultLocale;
40
        }
41
42
        $localeCode = $request->query->get('locale');
43
44
        if ($localeCode) {
45
            return $localeCode;
46
        }
47
48
        $preferredLanguage = $request->getPreferredLanguage();
49
50
        return empty($preferredLanguage) ? $this->defaultLocale : $preferredLanguage;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     * @codeCoverageIgnore
56
     */
57
    public function getLocale(): string
58
    {
59
        return $this->translator->getLocale();
60
    }
61
}
62