Passed
Pull Request — master (#383)
by
unknown
04:28
created

ResourceDeleteSubscriber::getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 4
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
 * another great project.
7
 * You can find more information about us on https://bitbag.shop and write us
8
 * an email on [email protected].
9
 */
10
11
declare(strict_types=1);
12
13
namespace BitBag\SyliusCmsPlugin\EventListener;
14
15
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
16
use Sylius\Component\Resource\ResourceActions;
17
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
18
use Symfony\Component\HttpFoundation\RedirectResponse;
19
use Symfony\Component\HttpFoundation\Request;
20
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
21
use Symfony\Component\HttpFoundation\Session\SessionInterface;
22
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
23
use Symfony\Component\HttpKernel\KernelEvents;
24
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
25
26
final class ResourceDeleteSubscriber implements EventSubscriberInterface
27
{
28
    /** @var UrlGeneratorInterface */
29
    private $router;
30
31
    /** @var SessionInterface */
32
    private $session;
33
34
    public function __construct(UrlGeneratorInterface $router, SessionInterface $session)
35
    {
36
        $this->router = $router;
37
        $this->session = $session;
38
    }
39
40
    public static function getSubscribedEvents(): array
41
    {
42
        return [
43
            KernelEvents::EXCEPTION => 'onResourceDelete',
44
        ];
45
    }
46
47
    public function onResourceDelete(ExceptionEvent $event): void
48
    {
49
        $exception = $event->getThrowable();
50
        if (!$exception instanceof ForeignKeyConstraintViolationException) {
51
            return;
52
        }
53
54
        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

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