1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of Sulu. |
5
|
|
|
* |
6
|
|
|
* (c) MASSIVE ART WebServices GmbH |
7
|
|
|
* |
8
|
|
|
* This source file is subject to the MIT license that is bundled |
9
|
|
|
* with this source code in the file LICENSE. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Sulu\Bundle\ValidationBundle\EventListener; |
13
|
|
|
|
14
|
|
|
use JsonSchema\Constraints\Factory; |
15
|
|
|
use JsonSchema\Validator; |
16
|
|
|
use Sulu\Bundle\ValidationBundle\JsonSchema\CachedSchemaStorageInterface; |
17
|
|
|
use Symfony\Component\HttpFoundation\Response; |
18
|
|
|
use Symfony\Component\HttpKernel\Event\GetResponseEvent; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* This listener checks for every request if a schema was defined for the current route. |
22
|
|
|
* If so, the requests data is validated by the given schema. |
23
|
|
|
*/ |
24
|
|
|
class ValidationRequestListener |
25
|
|
|
{ |
26
|
|
|
/** |
27
|
|
|
* @var array |
28
|
|
|
*/ |
29
|
|
|
private $schemas; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @var CachedSchemaStorageInterface |
33
|
|
|
*/ |
34
|
|
|
private $schemaStorage; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @param array $schemas |
38
|
|
|
* @param CachedSchemaStorageInterface $schemaStorage |
39
|
|
|
*/ |
40
|
9 |
|
public function __construct(array $schemas, CachedSchemaStorageInterface $schemaStorage) |
41
|
|
|
{ |
42
|
9 |
|
$this->schemas = $schemas; |
43
|
9 |
|
$this->schemaStorage = $schemaStorage; |
44
|
9 |
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param GetResponseEvent $event |
48
|
|
|
*/ |
49
|
9 |
|
public function onKernelRequest(GetResponseEvent $event) |
50
|
|
|
{ |
51
|
9 |
|
$request = $event->getRequest(); |
52
|
9 |
|
$routeId = $request->get('_route'); |
53
|
|
|
|
54
|
9 |
|
if (null === $routeId || !isset($this->schemas[$routeId])) { |
55
|
1 |
|
return; |
56
|
|
|
} |
57
|
|
|
|
58
|
8 |
|
$data = array_merge($request->request->all(), $request->query->all()); |
59
|
|
|
// FIXME: Validator should also be able to handle array data. |
60
|
|
|
// https://github.com/sulu/SuluValidationBundle/issues/3 |
61
|
8 |
|
$dataObject = json_decode(json_encode($data)); |
62
|
|
|
|
63
|
8 |
|
if (!$dataObject) { |
64
|
2 |
|
$dataObject = new \stdClass(); |
65
|
|
|
} |
66
|
|
|
|
67
|
8 |
|
$validator = new Validator(new Factory($this->schemaStorage)); |
68
|
8 |
|
$validator->check($dataObject, $this->schemaStorage->getSchemaByRoute($routeId)); |
69
|
|
|
|
70
|
8 |
|
if (!$validator->isValid()) { |
71
|
4 |
|
$event->setResponse(new Response(json_encode($validator->getErrors()), 400)); |
72
|
|
|
} |
73
|
8 |
|
} |
74
|
|
|
} |
75
|
|
|
|