Completed
Push — master ( 1c9f17...2589c5 )
by Kamil
21:28
created

ResourceDeleteSubscriber::isSyliusRoute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sylius\Bundle\AdminBundle\EventListener;
13
14
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
15
use Sylius\Component\Resource\ResourceActions;
16
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
17
use Symfony\Component\HttpFoundation\RedirectResponse;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\HttpFoundation\Session\SessionInterface;
20
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
21
use Symfony\Component\HttpKernel\KernelEvents;
22
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
23
24
/**
25
 * @author Jan Góralski <[email protected]>
26
 */
27
final class ResourceDeleteSubscriber implements EventSubscriberInterface
28
{
29
    /**
30
     * @var UrlGeneratorInterface
31
     */
32
    private $router;
33
34
    /**
35
     * @var SessionInterface
36
     */
37
    private $session;
38
39
    /**
40
     * @param UrlGeneratorInterface $router
41
     * @param SessionInterface $session
42
     */
43
    public function __construct(UrlGeneratorInterface $router, SessionInterface $session)
44
    {
45
        $this->router = $router;
46
        $this->session = $session;
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    public static function getSubscribedEvents()
53
    {
54
        return [
55
            KernelEvents::EXCEPTION => 'onResourceDelete',
56
        ];
57
    }
58
59
    /**
60
     * @param GetResponseForExceptionEvent $event
61
     */
62
    public function onResourceDelete(GetResponseForExceptionEvent $event)
63
    {
64
        $exception = $event->getException();
65
        if (!$exception instanceof ForeignKeyConstraintViolationException) {
66
            return;
67
        }
68
69
        if (!$event->isMasterRequest() || 'html' !== $event->getRequest()->getRequestFormat()) {
70
            return;
71
        }
72
73
        $eventRequest = $event->getRequest();
74
        $requestAttributes = $eventRequest->attributes;
75
        $originalRoute = $requestAttributes->get('_route');
76
77
        if (!$this->isMethodDelete($eventRequest) ||
78
            !$this->isSyliusRoute($originalRoute) ||
79
            !$this->isAdminSection($requestAttributes->get('_sylius', []))
80
        ) {
81
            return;
82
        }
83
84
        $resourceName = $this->getResourceNameFromRoute($originalRoute);
85
86
        if (null === $requestAttributes->get('_controller')) {
87
            return;
88
        }
89
90
        $this->session->getBag('flashes')->add('error', [
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\HttpFo...ion\SessionBagInterface as the method add() does only exist in the following implementations of said interface: Symfony\Component\HttpFo...lash\AutoExpireFlashBag, Symfony\Component\HttpFo...\Session\Flash\FlashBag.

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
            'message' => 'sylius.resource.delete_error',
92
            'parameters' => ['%resource%' => $resourceName],
93
        ]);
94
95
        $referrer = $eventRequest->headers->get('referer');
96
        if (null !== $referrer) {
97
            $event->setResponse(new RedirectResponse($referrer));
0 ignored issues
show
Bug introduced by
It seems like $referrer defined by $eventRequest->headers->get('referer') on line 95 can also be of type array; however, Symfony\Component\HttpFo...Response::__construct() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
98
99
            return;
100
        }
101
102
        $event->setResponse($this->createRedirectResponse($originalRoute, ResourceActions::INDEX));
103
    }
104
105
    /**
106
     * @param string $route
107
     *
108
     * @return string
109
     */
110
    private function getResourceNameFromRoute($route)
111
    {
112
        $routeArray = explode('_', $route);
113
        $routeArrayWithoutAction = array_slice($routeArray, 0, count($routeArray) - 1);
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $routeArrayWithoutAction exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
114
        $routeArrayWithoutPrefixes = array_slice($routeArrayWithoutAction, 2);
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $routeArrayWithoutPrefixes exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
115
116
        return trim(implode(' ', $routeArrayWithoutPrefixes));
117
    }
118
119
    /**
120
     * @param string $originalRoute
121
     * @param string $targetAction
122
     *
123
     * @return RedirectResponse
124
     */
125
    private function createRedirectResponse($originalRoute, $targetAction)
126
    {
127
        $redirectRoute = str_replace(ResourceActions::DELETE, $targetAction, $originalRoute);
128
129
        return new RedirectResponse($this->router->generate($redirectRoute));
130
    }
131
132
    /**
133
     * @param Request $request
134
     *
135
     * @return bool
136
     */
137
    private function isMethodDelete(Request $request)
138
    {
139
        return Request::METHOD_DELETE === $request->getMethod();
140
    }
141
142
    /**
143
     * @param string $route
144
     *
145
     * @return bool
146
     */
147
    private function isSyliusRoute($route)
148
    {
149
        return 0 === strpos($route, 'sylius');
150
    }
151
152
    /**
153
     * @param array $syliusParameters
154
     *
155
     * @return bool
156
     */
157
    private function isAdminSection(array $syliusParameters)
158
    {
159
        return array_key_exists('section', $syliusParameters) && 'admin' === $syliusParameters['section'];
160
    }
161
}
162