LocaleSubscriber   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 9
eloc 25
c 2
b 0
f 0
dl 0
loc 49
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A onKernelResponse() 0 7 2
A getSubscribedEvents() 0 6 1
A onKernelRequest() 0 21 5
A __construct() 0 3 1
1
<?php
2
3
namespace App\EventSubscriber;
4
5
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
6
use Symfony\Component\HttpFoundation\Cookie;
7
use Symfony\Component\HttpKernel\Event\RequestEvent;
8
use Symfony\Component\HttpKernel\Event\ResponseEvent;
9
use Symfony\Component\HttpKernel\KernelEvents;
10
11
class LocaleSubscriber implements EventSubscriberInterface
12
{
13
    private $defaultLocale;
14
15
    public function __construct($defaultLocale = 'en')
16
    {
17
        $this->defaultLocale = $defaultLocale;
18
    }
19
20
    public function onKernelRequest(RequestEvent $event)
21
    {
22
        $request = $event->getRequest();
23
        if (!$request->hasPreviousSession()) {
24
            return;
25
        }
26
27
        // try to see if the locale has been set as a _locale routing parameter or is present as a cookie
28
        if ($locale = $request->attributes->get('_locale')) {
29
            $request->setLocale($locale);
30
            $request->attributes->set('set_locale_cookie', $locale);
31
        } elseif ($locale = $request->query->get('_locale')) {
32
            $request->setLocale($locale);
33
            $request->attributes->set('set_locale_cookie', $locale);
34
        } elseif ($locale = $request->cookies->get('_locale')) {
35
            $request->setLocale($locale);
36
            $request->attributes->set('set_locale_cookie', $locale);
37
        } else {
38
            // if no explicit locale has been set on this request, use one from the cookie
39
            $request->setLocale($request->cookies->get('_locale', $this->defaultLocale));
40
            $request->attributes->set('set_locale_cookie', $this->defaultLocale);
41
        }
42
    }
43
44
    public function onKernelResponse(ResponseEvent $event)
45
    {
46
        $response = $event->getResponse();
47
        $request = $event->getRequest();
48
49
        if ($locale = $request->attributes->get('set_locale_cookie')) {
50
            $response->headers->setCookie(new Cookie('_locale', $locale, (new \DateTime())->modify('+1 year')));
51
        }
52
    }
53
54
    public static function getSubscribedEvents()
55
    {
56
        return [
57
            // must be registered before (i.e. with a higher priority than) the default Locale listener
58
            KernelEvents::REQUEST => [['onKernelRequest', 20]],
59
            KernelEvents::RESPONSE => [['onKernelResponse', 0]],
60
        ];
61
    }
62
}
63