Translator   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 55
rs 10
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A trans() 0 7 2
A loadCurrentLocale() 0 17 4
A __construct() 0 5 1
A setLocale() 0 3 1
A getLocale() 0 3 1
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
     * @codeCoverageIgnore
55
     */
56
    public function setLocale($locale = 'en'): void
57
    {
58
        $this->translator->setLocale($locale);
0 ignored issues
show
Bug introduced by
The method setLocale() does not exist on Symfony\Contracts\Translation\TranslatorInterface. It seems like you code against a sub-type of said class. However, the method does not exist in Symfony\Component\Transl...oLocalizationTranslator. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

58
        $this->translator->/** @scrutinizer ignore-call */ 
59
                           setLocale($locale);
Loading history...
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     * @codeCoverageIgnore
64
     */
65
    public function getLocale(): string
66
    {
67
        return $this->translator->getLocale();
68
    }
69
}
70