Completed
Push — master ( 13edef...d5b56b )
by Jeroen
85:52 queued 71:18
created

AdminLocaleListener::onKernelRequest()   B

Complexity

Conditions 9
Paths 4

Size

Total Lines 19

Duplication

Lines 3
Ratio 15.79 %

Code Coverage

Tests 8
CRAP Score 9

Importance

Changes 0
Metric Value
dl 3
loc 19
ccs 8
cts 8
cp 1
rs 8.0555
c 0
b 0
f 0
cc 9
nc 4
nop 1
crap 9
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\Event\ResponseEvent;
8
use Symfony\Component\HttpKernel\KernelEvents;
9
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
10
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
11
use Symfony\Component\Translation\TranslatorInterface;
12
use Kunstmaan\AdminBundle\Helper\AdminRouteHelper;
13
14
/**
15
 * AdminLocaleListener to override default locale if user-specific locale is set in database
16
 */
17
class AdminLocaleListener implements EventSubscriberInterface
18
{
19
    /**
20
     * @var TokenStorageInterface
21
     */
22
    private $tokenStorage;
23
24
    /**
25
     * @var TranslatorInterface
26
     */
27
    private $translator;
28
29
    /**
30
     * @var string
31
     */
32
    private $defaultAdminLocale;
33
34
    /**
35
     * @var string
36
     */
37
    private $providerKey;
38
39
    /**
40
     * @var AdminRouteHelper
41
     */
42
    private $adminRouteHelper;
43
44
    /**
45
     * @param TokenStorageInterface $tokenStorage
46
     * @param TranslatorInterface   $translator
47
     * @param string                $defaultAdminLocale
48
     * @param AdminRouteHelper      $adminRouteHelper
49
     * @param string                $providerKey        Firewall name to check against
50 1
     */
51
    public function __construct(TokenStorageInterface $tokenStorage, TranslatorInterface $translator, AdminRouteHelper $adminRouteHelper, $defaultAdminLocale, $providerKey = 'main')
52 1
    {
53 1
        $this->translator = $translator;
54 1
        $this->tokenStorage = $tokenStorage;
55 1
        $this->defaultAdminLocale = $defaultAdminLocale;
56 1
        $this->providerKey = $providerKey;
57 1
        $this->adminRouteHelper = $adminRouteHelper;
58
    }
59
60
    /**
61
     * onKernelRequest
62
     *
63
     * @param GetResponseEvent|ResponseEvent $event
64 1
     */
65
    public function onKernelRequest($event)
66 1
    {
67 1 View Code Duplication
        if (!$event instanceof GetResponseEvent && !$event instanceof ResponseEvent) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
68
            throw new \InvalidArgumentException(\sprintf('Expected instance of type %s, %s given', \class_exists(ResponseEvent::class) ? ResponseEvent::class : GetResponseEvent::class, \is_object($event) ? \get_class($event) : \gettype($event)));
69 1
        }
70 1
71
        $url = $event->getRequest()->getRequestUri();
72 1
        $token = $this->tokenStorage->getToken();
73 1
74
        if ($token && $this->isAdminToken($this->providerKey, $token) && $this->adminRouteHelper->isAdminRoute($url)) {
75
            $locale = $token->getUser()->getAdminLocale();
76 1
77
            if (!$locale) {
78 1
                $locale = $this->defaultAdminLocale;
79
            }
80
81
            $this->translator->setLocale($locale);
82
        }
83
    }
84
85
    /**
86 1
     * @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...
87
     * @param                $providerKey
88 1
     *
89
     * @return bool
90
     */
91
    private function isAdminToken($providerKey, TokenInterface $token = null)
92
    {
93
        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...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...
94 4
    }
95
96
    /**
97
     * getSubscribedEvents
98 4
     */
99
    public static function getSubscribedEvents()
100
    {
101
        return array(
102
            // Must be registered before the default Locale listener
103
            KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
104
        );
105
    }
106
}
107