Test Failed
Push — dev ( ccede5...b27119 )
by Herberto
13:46
created

AccessDeniedExceptionSubscriber::handleException()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Explicit Architecture POC,
7
 * which is created on top of the Symfony Demo application.
8
 *
9
 * (c) Herberto Graça <[email protected]>
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace Acme\App\Infrastructure\Auth\Authorization;
16
17
use Acme\App\Core\Port\Auth\AccessDeniedException;
18
use Acme\App\Core\Port\Persistence\TransactionServiceInterface;
19
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
20
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
21
use Symfony\Component\HttpKernel\KernelEvents;
22
use Symfony\Component\Security\Core\Exception\AccessDeniedException as SymfonyAccessDeniedException;
23
24
final class AccessDeniedExceptionSubscriber implements EventSubscriberInterface
25
{
26
    /**
27
     * @var TransactionServiceInterface
28
     */
29
    private $transactionService;
30
31
    public function __construct(TransactionServiceInterface $transactionService)
32
    {
33
        $this->transactionService = $transactionService;
34
    }
35
36
    /**
37
     * Return the subscribed events, their methods and possibly their priorities
38
     * (the higher the priority the earlier the method is called).
39
     *
40
     * @see http://symfony.com/doc/current/event_dispatcher.html#creating-an-event-subscriber
41
     */
42
    public static function getSubscribedEvents(): array
43
    {
44
        return [
45
            KernelEvents::EXCEPTION => ['handleException', 256],
46
        ];
47
    }
48
49
    public function handleException(GetResponseForExceptionEvent $event): void
50
    {
51
        $exception = $event->getException();
52
53
        switch (true) {
54
            case $exception instanceof AccessDeniedException:
55
                /*
56
                 * We translate our AccessDeniedException into Symfony AccessDeniedException,
57
                 * so that the system continues to respond in the same way, by redirecting to the login screen
58
                 */
59
                $newException = new SymfonyAccessDeniedException($exception->getMessage(), $exception);
60
                $newException->setAttributes(array_merge($exception->getRoleList(), [$exception->getAction()]));
61
                $newException->setSubject($exception->getSubject());
62
63
                $event->setException($newException);
64
65
                break;
66
        }
67
    }
68
}
69