|
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\InvalidRequestProblemExceptionInterface; |
|
17
|
|
|
use Nijens\OpenapiBundle\ExceptionHandling\Exception\RequestProblemExceptionInterface; |
|
18
|
|
|
use Nijens\OpenapiBundle\Routing\RouteContext; |
|
19
|
|
|
use Nijens\OpenapiBundle\Validation\RequestValidator\ValidatorInterface; |
|
20
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
|
21
|
|
|
use Symfony\Component\HttpFoundation\Request; |
|
22
|
|
|
use Symfony\Component\HttpKernel\Event\RequestEvent; |
|
23
|
|
|
use Symfony\Component\HttpKernel\KernelEvents; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Validates a request for routes loaded through the OpenAPI specification. |
|
27
|
|
|
* |
|
28
|
|
|
* @author Niels Nijens <[email protected]> |
|
29
|
|
|
*/ |
|
30
|
|
|
class RequestValidationSubscriber implements EventSubscriberInterface |
|
31
|
|
|
{ |
|
32
|
|
|
/** |
|
33
|
|
|
* @var ValidatorInterface |
|
34
|
|
|
*/ |
|
35
|
|
|
private $requestValidator; |
|
36
|
|
|
|
|
37
|
|
|
public static function getSubscribedEvents(): array |
|
38
|
|
|
{ |
|
39
|
|
|
return [ |
|
40
|
|
|
KernelEvents::REQUEST => [ |
|
41
|
|
|
['validateRequest', 28], |
|
42
|
|
|
], |
|
43
|
|
|
]; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
public function __construct(ValidatorInterface $requestValidator) |
|
47
|
|
|
{ |
|
48
|
|
|
$this->requestValidator = $requestValidator; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
public function validateRequest(RequestEvent $event): void |
|
52
|
|
|
{ |
|
53
|
|
|
$request = $event->getRequest(); |
|
54
|
|
|
if ($this->isManagedRoute($request) === false) { |
|
55
|
|
|
return; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
$exception = $this->requestValidator->validate($request); |
|
59
|
|
|
if ($exception instanceof RequestProblemExceptionInterface) { |
|
60
|
|
|
throw $exception; |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
private function isManagedRoute(Request $request): bool |
|
65
|
|
|
{ |
|
66
|
|
|
return $request->attributes->has(RouteContext::REQUEST_ATTRIBUTE); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|