LocaleSubscriber   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 18
c 0
b 0
f 0
dl 0
loc 46
rs 10
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getSubscribedEvents() 0 5 1
A __construct() 0 5 1
B onKernelRequest() 0 26 7
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Zikula package.
7
 *
8
 * Copyright Zikula - https://ziku.la/
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 Zikula\CoreBundle\EventSubscriber;
15
16
use Nucleos\UserBundle\Model\LocaleAwareUser;
17
use Symfony\Bundle\SecurityBundle\Security;
18
use Symfony\Component\DependencyInjection\Attribute\Autowire;
19
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
20
use Symfony\Component\HttpKernel\Event\RequestEvent;
21
use Symfony\Component\HttpKernel\KernelEvents;
22
23
class LocaleSubscriber implements EventSubscriberInterface
24
{
25
    public function __construct(
26
        private readonly Security $security,
27
        #[Autowire(param: 'kernel.default_locale')]
28
        private readonly string $defaultLocale
29
    ) {
30
    }
31
32
    public static function getSubscribedEvents(): array
33
    {
34
        return [
35
            // must be registered after the default Locale listener
36
            KernelEvents::REQUEST => ['onKernelRequest', 15],
37
        ];
38
    }
39
40
    /**
41
     * @see \Zikula\UsersBundle\EventListener\UserEventSubscriber
42
     */
43
    public function onKernelRequest(RequestEvent $event): void
44
    {
45
        $request = $event->getRequest();
46
        if (!$request->hasSession()) {
47
            return;
48
        }
49
        $session = $request->getSession();
50
        if (null === $session || !$request->hasPreviousSession()) {
51
            return;
52
        }
53
54
        // try to see if the locale has been set as a _locale routing parameter
55
        if ($locale = $request->attributes->get('_locale')) {
56
            $session->set('_locale', $locale);
57
        } else {
58
            // if no explicit locale has been set on this request, use one from the session or default
59
60
            // compute default locale considering user preference
61
            $userSelectedLocale = '';
62
            $user = $this->security->getUser();
63
            if ($user instanceof LocaleAwareUser) {
64
                $userSelectedLocale = $user->getLocale();
65
            }
66
            $defaultLocale = $userSelectedLocale ?: $this->defaultLocale;
0 ignored issues
show
Unused Code introduced by
The assignment to $defaultLocale is dead and can be removed.
Loading history...
67
68
            $request->setLocale($session->get('_locale', $this->defaultLocale));
69
        }
70
    }
71
}
72