|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types = 1); |
|
3
|
|
|
/** |
|
4
|
|
|
* /src/EventSubscriber/AcceptLanguageSubscriber.php |
|
5
|
|
|
* |
|
6
|
|
|
* @author TLe, Tarmo Leppänen <[email protected]> |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace App\EventSubscriber; |
|
10
|
|
|
|
|
11
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
|
12
|
|
|
use Symfony\Component\HttpKernel\Event\RequestEvent; |
|
13
|
|
|
use function in_array; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Class AcceptLanguageSubscriber |
|
17
|
|
|
* |
|
18
|
|
|
* @package App\EventSubscriber |
|
19
|
|
|
* @author TLe, Tarmo Leppänen <[email protected]> |
|
20
|
|
|
*/ |
|
21
|
|
|
class AcceptLanguageSubscriber implements EventSubscriberInterface |
|
22
|
|
|
{ |
|
23
|
|
|
// Supported locales |
|
24
|
|
|
public const LOCALE_EN = 'en'; |
|
25
|
|
|
public const LOCALE_FI = 'fi'; |
|
26
|
|
|
|
|
27
|
|
|
public const SUPPORTED_LOCALES = [ |
|
28
|
|
|
self::LOCALE_EN, |
|
29
|
|
|
self::LOCALE_FI, |
|
30
|
|
|
]; |
|
31
|
|
|
|
|
32
|
600 |
|
public function __construct( |
|
33
|
|
|
private readonly string $locale, |
|
34
|
|
|
) { |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* {@inheritdoc} |
|
39
|
|
|
* |
|
40
|
|
|
* @return array<string, array<int, string|int>> |
|
41
|
|
|
*/ |
|
42
|
1 |
|
public static function getSubscribedEvents(): array |
|
43
|
|
|
{ |
|
44
|
|
|
return [ |
|
45
|
|
|
RequestEvent::class => [ |
|
46
|
1 |
|
'onKernelRequest', |
|
47
|
|
|
// Note that this needs to at least `100` to get translation messages as expected |
|
48
|
|
|
100, |
|
49
|
|
|
], |
|
50
|
|
|
]; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Method to change used locale according to current request. |
|
55
|
|
|
*/ |
|
56
|
600 |
|
public function onKernelRequest(RequestEvent $event): void |
|
57
|
|
|
{ |
|
58
|
600 |
|
$request = $event->getRequest(); |
|
59
|
|
|
|
|
60
|
600 |
|
$locale = $request->headers->get('Accept-Language', $this->locale); |
|
61
|
|
|
|
|
62
|
|
|
// Ensure that given locale is supported, if not fallback to default. |
|
63
|
600 |
|
if (!in_array($locale, self::SUPPORTED_LOCALES, true)) { |
|
64
|
598 |
|
$locale = $this->locale; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
600 |
|
$request->setLocale($locale); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|