ValidationRequestListener::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 1
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