Completed
Push — master ( 91fdab...75a7b9 )
by
unknown
13:37
created

AdminBundle/EventListener/AdminLocaleListener.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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\RememberMeToken;
9
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
10
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
11
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
12
use Symfony\Component\Translation\TranslatorInterface;
13
use Kunstmaan\AdminBundle\Helper\AdminRouteHelper;
14
15
/**
16
 * AdminLocaleListener to override default locale if user-specific locale is set in database
17
 */
18
class AdminLocaleListener implements EventSubscriberInterface
19
{
20
    /**
21
     * @var TokenStorageInterface
22
     */
23
    private $tokenStorage;
24
25
    /**
26
     * @var TranslatorInterface
27
     */
28
    private $translator;
29
30
    /**
31
     * @var string
32
     */
33
    private $defaultAdminLocale;
34
35
    /**
36
     * @var string
37
     */
38
    private $providerKey;
39
40
    /**
41
     * @var AdminRouteHelper
42
     */
43
    private $adminRouteHelper;
44
45
    /**
46
     * @param TokenStorageInterface $tokenStorage
47
     * @param TranslatorInterface   $translator
48
     * @param string                $defaultAdminLocale
49
     * @param AdminRouteHelper      $adminRouteHelper
50
     * @param string                $providerKey          Firewall name to check against
51
     */
52
    public function __construct(TokenStorageInterface $tokenStorage, TranslatorInterface $translator, AdminRouteHelper $adminRouteHelper, $defaultAdminLocale, $providerKey = 'main')
53
    {
54
        $this->translator         = $translator;
55
        $this->tokenStorage       = $tokenStorage;
56
        $this->defaultAdminLocale = $defaultAdminLocale;
57
        $this->providerKey        = $providerKey;
58
        $this->adminRouteHelper   = $adminRouteHelper;
59
    }
60
61
    /**
62
     * onKernelRequest
63
     *
64
     * @param GetResponseEvent $event
65
     */
66
    public function onKernelRequest(GetResponseEvent $event)
67
    {
68
        $url = $event->getRequest()->getRequestUri();
69
        $token = $this->tokenStorage->getToken();
70
71
        if ($token && $this->isAdminToken($this->providerKey, $token) && $this->adminRouteHelper->isAdminRoute($url)) {
72
            $locale = $token->getUser()->getAdminLocale();
73
74
            if (!$locale) {
75
                $locale = $this->defaultAdminLocale;
76
            }
77
78
            $this->translator->setLocale($locale);
79
        }
80
    }
81
82
    /**
83
     * @param TokenInterface $token
84
     * @param                $providerKey
85
     *
86
     * @return bool
87
     */
88
    private function isAdminToken($providerKey, TokenInterface $token = null)
89
    {
90
        return is_callable([$token, 'getProviderKey']) && $token->getProviderKey() === $providerKey;
0 ignored issues
show
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\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...
91
    }
92
93
    /**
94
     * getSubscribedEvents
95
     */
96
    static public function getSubscribedEvents()
97
    {
98
        return array(
99
            // Must be registered before the default Locale listener
100
            KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
101
        );
102
    }
103
}
104