Completed
Pull Request — 2.x (#251)
by
unknown
02:57
created

LocaleSubscriber::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sonata\TranslationBundle\EventSubscriber;
13
14
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
15
use Symfony\Component\HttpKernel\KernelEvents;
16
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
17
18
/**
19
 * Locale subscriber.
20
 *
21
 * @author Jonathan Vautrin <[email protected]>
22
 */
23
final class LocaleSubscriber implements EventSubscriberInterface
24
{
25
    /**
26
     * @var string
27
     */
28
    private $defaultLocale;
29
30
    /**
31
     * @param string $defaultLocale
32
     */
33
    public function __construct($defaultLocale = 'en')
34
    {
35
        $this->defaultLocale = $defaultLocale;
36
    }
37
38
    /**
39
     * @param GetResponseEvent $event
40
     */
41
    public function onKernelRequest(GetResponseEvent $event)
42
    {
43
        $request = $event->getRequest();
44
        if (!$request->hasPreviousSession()) {
45
            return;
46
        }
47
48
        // try to see if the locale has been set as a _locale routing parameter
49
        if ($locale = $request->attributes->get('_locale')) {
50
            $request->getSession()->set('_locale', $locale);
51
            return;
52
        }
53
54
        // if no explicit locale has been set on this request, use one from the session
55
        $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
56
    }
57
58
    /**
59
     * @return array
60
     */
61
    public static function getSubscribedEvents()
62
    {
63
        return array(
64
            // must be registered before (i.e. with a higher priority than) the default Locale listener
65
            KernelEvents::REQUEST => [['onKernelRequest', 20]],
66
        );
67
    }
68
}
69