|
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
|
|
|
public function onKernelRequest(GetResponseEvent $event): void |
|
39
|
|
|
{ |
|
40
|
|
|
$request = $event->getRequest(); |
|
41
|
|
|
if (!$request->hasPreviousSession()) { |
|
42
|
|
|
return; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
// try to see if the locale has been set as a _locale routing parameter |
|
46
|
|
|
if ($locale = $request->attributes->get('_locale')) { |
|
47
|
|
|
$request->getSession()->set('_locale', $locale); |
|
48
|
|
|
|
|
49
|
|
|
return; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
// if no explicit locale has been set on this request, use one from the session |
|
53
|
|
|
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale)); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* @return array |
|
58
|
|
|
*/ |
|
59
|
|
|
public static function getSubscribedEvents() |
|
60
|
|
|
{ |
|
61
|
|
|
return [ |
|
62
|
|
|
// must be registered before (i.e. with a higher priority than) the default Locale listener |
|
63
|
|
|
KernelEvents::REQUEST => [['onKernelRequest', 20]], |
|
64
|
|
|
]; |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|