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
|
|
|
|