Completed
Pull Request — 2.x (#251)
by
unknown
01:50
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
class LocaleSubscriber implements EventSubscriberInterface
24
{
25
    /**
26
     * The default locale.
27
     *
28
     * @var string
29
     */
30
    private $defaultLocale;
31
32
    /**
33
     * @param string $defaultLocale
34
     */
35
    public function __construct(string $defaultLocale = 'en')
36
    {
37
        $this->defaultLocale = $defaultLocale;
38
    }
39
40
    /**
41
     * Kernel request.
42
     *
43
     * @param GetResponseEvent $event
44
     */
45
    public function onKernelRequest(GetResponseEvent $event)
46
    {
47
        $request = $event->getRequest();
48
        if (!$request->hasPreviousSession()) {
49
            return;
50
        }
51
52
        // try to see if the locale has been set as a _locale routing parameter
53
        if ($locale = $request->attributes->get('_locale')) {
54
            $request->getSession()->set('_locale', $locale);
55
        } else {
56
            // if no explicit locale has been set on this request, use one from the session
57
            $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
58
        }
59
    }
60
61
    /**
62
     * Subscribed events.
63
     *
64
     * @return array
65
     */
66
    public static function getSubscribedEvents()
67
    {
68
        return array(
69
            // must be registered before (i.e. with a higher priority than) the default Locale listener
70
            KernelEvents::REQUEST => array(array('onKernelRequest', 20)),
71
        );
72
    }
73
}
74