Completed
Push — bring-back-validation-groups ( e1fc79...5a8a4f )
by Kamil
20:58
created

ResourceDeleteSubscriber::isAdminSection()   A

Complexity

Conditions 2
Paths 2

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 2
eloc 2
nc 2
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\ResourceBundle\EventListener;
13
14
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
15
use FOS\RestBundle\View\View;
16
use FOS\RestBundle\View\ViewHandlerInterface as RestViewHandlerInterface;
17
use Sylius\Component\Resource\ResourceActions;
18
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
19
use Symfony\Component\HttpFoundation\RedirectResponse;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpFoundation\Response;
22
use Symfony\Component\HttpFoundation\Session\SessionInterface;
23
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
24
use Symfony\Component\HttpKernel\KernelEvents;
25
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
26
use Symfony\Component\Translation\TranslatorInterface;
27
28
/**
29
 * @author Jan Góralski <[email protected]>
30
 */
31
final class ResourceDeleteSubscriber implements EventSubscriberInterface
32
{
33
    /**
34
     * @var UrlGeneratorInterface
35
     */
36
    private $router;
37
38
    /**
39
     * @var SessionInterface
40
     */
41
    private $session;
42
43
    /**
44
     * @var TranslatorInterface
45
     */
46
    private $translator;
47
48
    /**
49
     * @var RestViewHandlerInterface
50
     */
51
    private $viewHandler;
52
53
    /**
54
     * @param UrlGeneratorInterface $router
55
     * @param SessionInterface $session
56
     * @param TranslatorInterface $translator
57
     * @param RestViewHandlerInterface $viewHandler
58
     */
59
    public function __construct(
60
        UrlGeneratorInterface $router,
61
        SessionInterface $session,
62
        TranslatorInterface $translator,
63
        RestViewHandlerInterface $viewHandler
64
    ) {
65
        $this->router = $router;
66
        $this->session = $session;
67
        $this->translator = $translator;
68
        $this->viewHandler = $viewHandler;
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    public static function getSubscribedEvents()
75
    {
76
        return [
77
            KernelEvents::EXCEPTION => 'onResourceDelete',
78
        ];
79
    }
80
81
    /**
82
     * @param GetResponseForExceptionEvent $event
83
     */
84
    public function onResourceDelete(GetResponseForExceptionEvent $event)
85
    {
86
        $exception = $event->getException();
87
        if (!$exception instanceof ForeignKeyConstraintViolationException) {
88
            return;
89
        }
90
91
        if (!$event->isMasterRequest()) {
92
            return;
93
        }
94
95
        $eventRequest = $event->getRequest();
96
        $requestAttributes = $eventRequest->attributes;
97
        $originalRoute = $requestAttributes->get('_route');
98
99
        if (!$this->isMethodDelete($eventRequest) ||
100
            !$this->isSyliusRoute($originalRoute) ||
101
            !$this->isAdminSection($requestAttributes->get('_sylius', []))
102
        ) {
103
            return;
104
        }
105
106
        $resourceName = $this->getResourceNameFromRoute($originalRoute);
107
108
        $message = $this->translator->trans('sylius.resource.delete_error', ['%resource%' => $resourceName], 'flashes');
109
110
        if (!$this->isHtmlRequest($eventRequest)) {
111
            $event->setResponse(
112
                $this->viewHandler->handle(View::create([
113
                    'error' => [
114
                        'code' => $exception->getSQLState(),
115
                        'message' => $message,
116
                    ],
117
                ], Response::HTTP_METHOD_NOT_ALLOWED))
118
            );
119
120
            return;
121
        }
122
123
        if (null === $requestAttributes->get('_controller')) {
124
            return;
125
        }
126
127
        $this->session->getBag('flashes')->add('error', $message);
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...
128
129
        $referrer = $eventRequest->headers->get('referer');
130
        if (null !== $referrer) {
131
            $event->setResponse(new RedirectResponse($referrer));
0 ignored issues
show
Bug introduced by
It seems like $referrer defined by $eventRequest->headers->get('referer') on line 129 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...
132
133
            return;
134
        }
135
136
        $event->setResponse($this->createRedirectResponse($originalRoute, ResourceActions::INDEX));
137
    }
138
139
    /**
140
     * @param string $route
141
     *
142
     * @return string
143
     */
144
    private function getResourceNameFromRoute($route)
145
    {
146
        $routeArray = explode('_', $route);
147
        $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...
148
        $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...
149
150
        return trim(implode(' ', $routeArrayWithoutPrefixes));
151
    }
152
153
    /**
154
     * @param string $originalRoute
155
     * @param string $targetAction
156
     *
157
     * @return RedirectResponse
158
     */
159
    private function createRedirectResponse($originalRoute, $targetAction)
160
    {
161
        $redirectRoute = str_replace(ResourceActions::DELETE, $targetAction, $originalRoute);
162
163
        return new RedirectResponse($this->router->generate($redirectRoute));
164
    }
165
166
    /**
167
     * @param Request $request
168
     *
169
     * @return bool
170
     */
171
    private function isHtmlRequest(Request $request)
172
    {
173
        return 'html' === $request->getRequestFormat();
174
    }
175
176
    /**
177
     * @param Request $request
178
     *
179
     * @return bool
180
     */
181
    private function isMethodDelete(Request $request)
182
    {
183
        return Request::METHOD_DELETE === $request->getMethod();
184
    }
185
186
    /**
187
     * @param string $route
188
     *
189
     * @return bool
190
     */
191
    private function isSyliusRoute($route)
192
    {
193
        return 0 === strpos($route, 'sylius');
194
    }
195
196
    /**
197
     * @param array $syliusParameters
198
     *
199
     * @return bool
200
     */
201
    private function isAdminSection(array $syliusParameters)
202
    {
203
        return array_key_exists('section', $syliusParameters) && 'admin' === $syliusParameters['section'];
204
    }
205
}
206