Passed
Push — main ( b15a24...935ae5 )
by Axel
04:15
created

LocaleSubscriber::onKernelRequest()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 15
nc 5
nop 1
dl 0
loc 26
rs 9.2222
c 0
b 0
f 0
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\Bundle\CoreBundle\EventSubscriber;
15
16
use Nucleos\UserBundle\Model\LocaleAwareUser;
17
use Symfony\Bundle\SecurityBundle\Security;
18
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
19
use Symfony\Component\HttpKernel\Event\RequestEvent;
20
use Symfony\Component\HttpKernel\KernelEvents;
21
22
class LocaleSubscriber implements EventSubscriberInterface
23
{
24
    public function __construct(
25
        private readonly Security $security,
26
        private readonly string $defaultLocale = 'en'
27
    ) {
28
    }
29
30
    public static function getSubscribedEvents(): array
31
    {
32
        return [
33
            // must be registered after the default Locale listener
34
            KernelEvents::REQUEST => ['onKernelRequest', 15],
35
        ];
36
    }
37
38
    /**
39
     * @see \Zikula\UsersBundle\EventListener\UserEventSubscriber
40
     */
41
    public function onKernelRequest(RequestEvent $event): void
42
    {
43
        $request = $event->getRequest();
44
        if (!$request->hasSession()) {
45
            return;
46
        }
47
        $session = $request->getSession();
48
        if (null === $session || !$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
            $session->set('_locale', $locale);
55
        } else {
56
            // if no explicit locale has been set on this request, use one from the session or default
57
58
            // compute default locale considering user preference
59
            $userSelectedLocale = '';
60
            $user = $this->security->getUser();
61
            if ($user instanceof LocaleAwareUser) {
62
                $userSelectedLocale = $user->getLocale();
63
            }
64
            $defaultLocale = $userSelectedLocale ?? $this->defaultLocale;
0 ignored issues
show
Unused Code introduced by
The assignment to $defaultLocale is dead and can be removed.
Loading history...
65
66
            $request->setLocale($session->get('_locale', $this->defaultLocale));
67
        }
68
    }
69
}
70