1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Nicofuma\SwaggerBundle\EventListener; |
4
|
|
|
|
5
|
|
|
use Nicofuma\SwaggerBundle\Exception\ConstraintViolationException; |
6
|
|
|
use Nicofuma\SwaggerBundle\Exception\NoValidatorException; |
7
|
|
|
use Nicofuma\SwaggerBundle\Validator\ValidatorMap; |
8
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
9
|
|
|
use Symfony\Component\HttpKernel\Event\GetResponseEvent; |
10
|
|
|
use Symfony\Component\HttpKernel\KernelEvents; |
11
|
|
|
use Symfony\Component\Validator\ConstraintViolation; |
12
|
|
|
use Symfony\Component\Validator\ConstraintViolationList; |
13
|
|
|
|
14
|
|
|
class ValidatorListener implements EventSubscriberInterface |
15
|
|
|
{ |
16
|
|
|
/** @var ValidatorMap */ |
17
|
|
|
private $map; |
18
|
|
|
|
19
|
3 |
|
public function __construct(ValidatorMap $map) |
20
|
|
|
{ |
21
|
3 |
|
$this->map = $map; |
22
|
3 |
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Handles swgger validations. |
26
|
|
|
* |
27
|
|
|
* @param GetResponseEvent $event An GetResponseEvent instance |
28
|
|
|
*/ |
29
|
3 |
|
public function onKernelRequest(GetResponseEvent $event) |
30
|
|
|
{ |
31
|
|
|
// Workaround for https://github.com/symfony/symfony/issues/19749 |
32
|
3 |
|
if (!$event->isMasterRequest()) { |
33
|
|
|
return; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
try { |
37
|
3 |
|
$request = $event->getRequest(); |
38
|
3 |
|
$validator = $this->map->getValidator($request); |
39
|
2 |
|
$validator->validate($request); |
40
|
3 |
|
} catch (NoValidatorException $e) { |
41
|
|
|
// Do nothing |
42
|
2 |
|
} catch (\PHPUnit_Framework_ExpectationFailedException $e) { |
43
|
1 |
|
$violationMessages = explode("\n", $e->getMessage()); |
44
|
1 |
|
array_shift($violationMessages); |
45
|
1 |
|
array_pop($violationMessages); |
46
|
1 |
|
$violations = new ConstraintViolationList(); |
47
|
|
|
|
48
|
1 |
|
foreach ($violationMessages as $violationMessage) { |
49
|
1 |
|
list($path, $message) = explode(' ', $violationMessage, 2); |
50
|
|
|
|
51
|
1 |
|
$violations->add(new ConstraintViolation( |
52
|
1 |
|
$message, |
53
|
1 |
|
$message, |
54
|
1 |
|
[], |
55
|
1 |
|
null, |
56
|
1 |
|
$path, |
57
|
|
|
null |
58
|
1 |
|
)); |
59
|
1 |
|
} |
60
|
|
|
|
61
|
1 |
|
throw new ConstraintViolationException($violations); |
62
|
|
|
} |
63
|
2 |
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* {@inheritdoc} |
67
|
|
|
*/ |
68
|
|
|
public static function getSubscribedEvents() |
69
|
|
|
{ |
70
|
|
|
return [ |
71
|
|
|
KernelEvents::REQUEST => ['onKernelRequest', 128], |
72
|
|
|
]; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|