1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the Sonata Project package. |
7
|
|
|
* |
8
|
|
|
* (c) Thomas Rabaix <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Sonata\TranslationBundle\EventSubscriber; |
15
|
|
|
|
16
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
17
|
|
|
use Symfony\Component\HttpKernel\Event\GetResponseEvent; |
18
|
|
|
use Symfony\Component\HttpKernel\KernelEvents; |
19
|
|
|
|
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): void |
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
|
|
|
|
52
|
|
|
return; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
// if no explicit locale has been set on this request, use one from the session |
56
|
|
|
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale)); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @return array |
61
|
|
|
*/ |
62
|
|
|
public static function getSubscribedEvents() |
63
|
|
|
{ |
64
|
|
|
return [ |
65
|
|
|
// must be registered before (i.e. with a higher priority than) the default Locale listener |
66
|
|
|
KernelEvents::REQUEST => [['onKernelRequest', 20]], |
67
|
|
|
]; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|