RequestValidationSubscriber   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
dl 0
loc 37
rs 10
c 1
b 0
f 0
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getSubscribedEvents() 0 5 1
A __construct() 0 3 1
A isManagedRoute() 0 3 1
A validateRequest() 0 10 3
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the OpenapiBundle package.
7
 *
8
 * (c) Niels Nijens <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Nijens\OpenapiBundle\Validation\EventSubscriber;
15
16
use Nijens\OpenapiBundle\ExceptionHandling\Exception\RequestProblemExceptionInterface;
17
use Nijens\OpenapiBundle\Routing\RouteContext;
18
use Nijens\OpenapiBundle\Validation\RequestValidator\ValidatorInterface;
19
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpKernel\Event\RequestEvent;
22
use Symfony\Component\HttpKernel\KernelEvents;
23
24
/**
25
 * Validates a request for routes loaded through the OpenAPI specification.
26
 *
27
 * @author Niels Nijens <[email protected]>
28
 */
29
class RequestValidationSubscriber implements EventSubscriberInterface
30
{
31
    /**
32
     * @var ValidatorInterface
33
     */
34
    private $requestValidator;
35
36
    public static function getSubscribedEvents(): array
37
    {
38
        return [
39
            KernelEvents::REQUEST => [
40
                ['validateRequest', 7],
41
            ],
42
        ];
43
    }
44
45
    public function __construct(ValidatorInterface $requestValidator)
46
    {
47
        $this->requestValidator = $requestValidator;
48
    }
49
50
    public function validateRequest(RequestEvent $event): void
51
    {
52
        $request = $event->getRequest();
53
        if ($this->isManagedRoute($request) === false) {
54
            return;
55
        }
56
57
        $exception = $this->requestValidator->validate($request);
58
        if ($exception instanceof RequestProblemExceptionInterface) {
59
            throw $exception;
60
        }
61
    }
62
63
    private function isManagedRoute(Request $request): bool
64
    {
65
        return $request->attributes->has(RouteContext::REQUEST_ATTRIBUTE);
66
    }
67
}
68