LocaleSubscriber::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Victoire\Bundle\I18nBundle\Subscriber;
4
5
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
6
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
7
use Symfony\Component\HttpKernel\KernelEvents;
8
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
9
use Symfony\Component\Security\Http\SecurityEvents;
10
use Victoire\Bundle\UserBundle\Model\VictoireUserInterface;
11
12
class LocaleSubscriber implements EventSubscriberInterface
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
13
{
14
    private $defaultLocale;
15
16
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$defaultLocale" missing
Loading history...
17
     * Constructor.
18
     *
19
     * @param $defaultLocale the default locale of the application
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
20
     */
21
    public function __construct($defaultLocale)
22
    {
23
        $this->defaultLocale = $defaultLocale;
24
    }
25
26
    /**
27
     * @param GetResponseEvent $event
28
     *
29
     * method called on kernel request used only to persist locale in session
30
     */
31
    public function onKernelRequest(GetResponseEvent $event)
32
    {
33
        $request = $event->getRequest();
34
        if (!$request->hasPreviousSession()) {
35
            return;
36
        }
37
38
        //see if the _locale routing parameter is set
39
        if ($locale = $request->getLocale()) {
40
            $request->getSession()->set('_locale', $locale);
41
            $request->setLocale($locale);
42
        } else {
43
            // use the session's one
44
            $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
45
        }
46
    }
47
48
    /**
49
     * This method will be called on user login in order to set the victoire locale.
50
     *
51
     * @param InteractiveLoginEvent $event
52
     */
53
    public function onLogin(InteractiveLoginEvent $event)
54
    {
55
        $user = $event->getAuthenticationToken()->getUser();
56
57
        if ($user instanceof VictoireUserInterface) {
58
            // set the victoireLocale
59
            $event->getRequest()->getSession()->set('victoire_locale', $user->getLocale());
60
        }
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    public static function getSubscribedEvents()
67
    {
68
        return [
69
            SecurityEvents::INTERACTIVE_LOGIN => 'onLogin',
70
            KernelEvents::REQUEST             => 'onKernelRequest',
71
        ];
72
    }
73
}
74