Passed
Push — master ( ae2edc...eec2e9 )
by Damian
04:09
created

ResourceDeleteSubscriber::isAdminSection()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 1
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
/*
4
 * This file has been created by developers from BitBag.
5
 * Feel free to contact us once you face any issues or want to start
6
 * You can find more information about us on https://bitbag.io and write us
7
 * an email on [email protected].
8
 */
9
10
declare(strict_types=1);
11
12
namespace BitBag\SyliusCmsPlugin\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\Flash\FlashBagInterface;
20
use Symfony\Component\HttpFoundation\Session\SessionInterface;
21
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
22
use Symfony\Component\HttpKernel\KernelEvents;
23
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
24
25
final class ResourceDeleteSubscriber implements EventSubscriberInterface
26
{
27
    /** @var UrlGeneratorInterface */
28
    private $router;
29
30
    /** @var SessionInterface */
31
    private $session;
32
33
    public function __construct(UrlGeneratorInterface $router, SessionInterface $session)
34
    {
35
        $this->router = $router;
36
        $this->session = $session;
37
    }
38
39
    public static function getSubscribedEvents(): array
40
    {
41
        return [
42
            KernelEvents::EXCEPTION => 'onResourceDelete',
43
        ];
44
    }
45
46
    public function onResourceDelete(ExceptionEvent $event): void
47
    {
48
        $exception = $event->getThrowable();
49
        if (!$exception instanceof ForeignKeyConstraintViolationException) {
50
            return;
51
        }
52
53
        if (!$event->isMasterRequest() || 'html' !== $event->getRequest()->getRequestFormat()) {
0 ignored issues
show
Deprecated Code introduced by
The function Symfony\Component\HttpKe...vent::isMasterRequest() has been deprecated: since symfony/http-kernel 5.3, use isMainRequest() instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

53
        if (!/** @scrutinizer ignore-deprecated */ $event->isMasterRequest() || 'html' !== $event->getRequest()->getRequestFormat()) {

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
54
            return;
55
        }
56
57
        $eventRequest = $event->getRequest();
58
        $requestAttributes = $eventRequest->attributes;
59
        $originalRoute = $requestAttributes->get('_route');
60
61
        if (!$this->isMethodDelete($eventRequest) ||
62
            !$this->isProtectedRoute($originalRoute) ||
63
            !$this->isAdminSection($requestAttributes->get('_sylius', []))
64
        ) {
65
            return;
66
        }
67
68
        $resourceName = $this->getResourceNameFromRoute($originalRoute);
69
70
        if (null === $requestAttributes->get('_controller')) {
71
            return;
72
        }
73
74
        /** @var FlashBagInterface $flashBag */
75
        $flashBag = $this->session->getBag('flashes');
76
        $flashBag->add('error', [
77
            'message' => 'sylius.resource.delete_error',
78
            'parameters' => ['%resource%' => $resourceName],
79
        ]);
80
81
        $referrer = $eventRequest->headers->get('referer');
82
        if (null !== $referrer) {
0 ignored issues
show
introduced by
The condition null !== $referrer is always true.
Loading history...
83
            $event->setResponse(new RedirectResponse($referrer));
84
85
            return;
86
        }
87
88
        $event->setResponse($this->createRedirectResponse($originalRoute, ResourceActions::INDEX));
89
    }
90
91
    private function getResourceNameFromRoute(string $route): string
92
    {
93
        $route = str_replace('_bulk', '', $route);
94
        $routeArray = explode('_', $route);
95
        $routeArrayWithoutAction = array_slice($routeArray, 0, count($routeArray) - 1);
96
        $routeArrayWithoutPrefixes = array_slice($routeArrayWithoutAction, 2);
97
98
        return trim(implode(' ', $routeArrayWithoutPrefixes));
99
    }
100
101
    private function createRedirectResponse(string $originalRoute, string $targetAction): RedirectResponse
102
    {
103
        $redirectRoute = str_replace(ResourceActions::DELETE, $targetAction, $originalRoute);
104
105
        return new RedirectResponse($this->router->generate($redirectRoute));
106
    }
107
108
    private function isMethodDelete(Request $request): bool
109
    {
110
        return Request::METHOD_DELETE === $request->getMethod();
111
    }
112
113
    private function isProtectedRoute(string $route): bool
114
    {
115
        return 0 === strpos($route, 'bitbag');
116
    }
117
118
    private function isAdminSection(array $syliusParameters): bool
119
    {
120
        return array_key_exists('section', $syliusParameters) && 'admin' === $syliusParameters['section'];
121
    }
122
}
123