Completed
Push — 5.3 ( d18aef...16c32d )
by Jeroen
15:04 queued 08:59
created

AdminLocaleListener::getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Kunstmaan\AdminBundle\EventListener;
4
5
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
6
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
7
use Symfony\Component\HttpKernel\KernelEvents;
8
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
9
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
10
use Symfony\Component\Translation\TranslatorInterface;
11
use Kunstmaan\AdminBundle\Helper\AdminRouteHelper;
12
13
/**
14
 * AdminLocaleListener to override default locale if user-specific locale is set in database
15
 */
16
class AdminLocaleListener implements EventSubscriberInterface
17
{
18
    /**
19
     * @var TokenStorageInterface
20
     */
21
    private $tokenStorage;
22
23
    /**
24
     * @var TranslatorInterface
25
     */
26
    private $translator;
27
28
    /**
29
     * @var string
30
     */
31
    private $defaultAdminLocale;
32
33
    /**
34
     * @var string
35
     */
36
    private $providerKey;
37
38
    /**
39
     * @var AdminRouteHelper
40
     */
41
    private $adminRouteHelper;
42
43
    /**
44
     * @param TokenStorageInterface $tokenStorage
45
     * @param TranslatorInterface   $translator
46
     * @param string                $defaultAdminLocale
47
     * @param AdminRouteHelper      $adminRouteHelper
48
     * @param string                $providerKey        Firewall name to check against
49
     */
50 1
    public function __construct(TokenStorageInterface $tokenStorage, TranslatorInterface $translator, AdminRouteHelper $adminRouteHelper, $defaultAdminLocale, $providerKey = 'main')
51
    {
52 1
        $this->translator = $translator;
53 1
        $this->tokenStorage = $tokenStorage;
54 1
        $this->defaultAdminLocale = $defaultAdminLocale;
55 1
        $this->providerKey = $providerKey;
56 1
        $this->adminRouteHelper = $adminRouteHelper;
57 1
    }
58
59
    /**
60
     * onKernelRequest
61
     *
62
     * @param GetResponseEvent $event
63
     */
64 1
    public function onKernelRequest(GetResponseEvent $event)
65
    {
66 1
        $url = $event->getRequest()->getRequestUri();
67 1
        $token = $this->tokenStorage->getToken();
68
69 1
        if ($token && $this->isAdminToken($this->providerKey, $token) && $this->adminRouteHelper->isAdminRoute($url)) {
70 1
            $locale = $token->getUser()->getAdminLocale();
71
72 1
            if (!$locale) {
73 1
                $locale = $this->defaultAdminLocale;
74
            }
75
76 1
            $this->translator->setLocale($locale);
77
        }
78 1
    }
79
80
    /**
81
     * @param TokenInterface $token
0 ignored issues
show
Documentation introduced by
Should the type for parameter $token not be null|TokenInterface?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
82
     * @param                $providerKey
83
     *
84
     * @return bool
85
     */
86 1
    private function isAdminToken($providerKey, TokenInterface $token = null)
87
    {
88 1
        return is_callable([$token, 'getProviderKey']) && $token->getProviderKey() === $providerKey;
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Securi...on\Token\TokenInterface as the method getProviderKey() does only exist in the following implementations of said interface: Symfony\Component\Securi...n\PreAuthenticatedToken, Symfony\Component\Securi...n\Token\RememberMeToken, Symfony\Component\Securi...n\Token\SwitchUserToken, Symfony\Component\Securi...n\UsernamePasswordToken, Symfony\Component\Securi...alCustomRememberMeToken, Symfony\Component\Securi...uthenticationGuardToken.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
89
    }
90
91
    /**
92
     * getSubscribedEvents
93
     */
94 4
    public static function getSubscribedEvents()
95
    {
96
        return array(
97
            // Must be registered before the default Locale listener
98 4
            KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
99
        );
100
    }
101
}
102