Completed
Push — master ( ddaf69...154218 )
by Tarmo
17s queued 13s
created

AcceptLanguageSubscriber::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 1
dl 0
loc 3
ccs 1
cts 1
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types = 1);
3
/**
4
 * /src/EventSubscriber/AcceptLanguageSubscriber.php
5
 *
6
 * @author TLe, Tarmo Leppänen <[email protected]>
7
 */
8
9
namespace App\EventSubscriber;
10
11
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
12
use Symfony\Component\HttpKernel\Event\RequestEvent;
13
use function in_array;
14
15
/**
16
 * Class AcceptLanguageSubscriber
17
 *
18
 * @package App\EventSubscriber
19
 * @author TLe, Tarmo Leppänen <[email protected]>
20
 */
21
class AcceptLanguageSubscriber implements EventSubscriberInterface
22
{
23
    // Supported locales
24
    public const LOCALE_EN = 'en';
25
    public const LOCALE_FI = 'fi';
26
27
    public const SUPPORTED_LOCALES = [
28
        self::LOCALE_EN,
29
        self::LOCALE_FI,
30
    ];
31
32 600
    public function __construct(
33
        private readonly string $locale,
34
    ) {
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     *
40
     * @return array<string, array<int, string|int>>
41
     */
42 1
    public static function getSubscribedEvents(): array
43
    {
44
        return [
45
            RequestEvent::class => [
46 1
                'onKernelRequest',
47
                // Note that this needs to at least `100` to get translation messages as expected
48
                100,
49
            ],
50
        ];
51
    }
52
53
    /**
54
     * Method to change used locale according to current request.
55
     */
56 600
    public function onKernelRequest(RequestEvent $event): void
57
    {
58 600
        $request = $event->getRequest();
59
60 600
        $locale = $request->headers->get('Accept-Language', $this->locale);
61
62
        // Ensure that given locale is supported, if not fallback to default.
63 600
        if (!in_array($locale, self::SUPPORTED_LOCALES, true)) {
64 598
            $locale = $this->locale;
65
        }
66
67 600
        $request->setLocale($locale);
68
    }
69
}
70