Completed
Push — master ( 07e238...0f15f1 )
by Pavel
09:14
created

JmsValidatorSubscriber::getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 0
crap 1
1
<?php
2
3
namespace ScayTrase\Api\Cruds\Adaptors\JmsSerializer;
4
5
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
6
use JMS\Serializer\EventDispatcher\ObjectEvent;
7
use ScayTrase\Api\Cruds\Exception\EntityProcessingException;
8
use Symfony\Component\Validator\ConstraintViolationInterface;
9
use Symfony\Component\Validator\Validator\ValidatorInterface;
10
11
final class JmsValidatorSubscriber implements EventSubscriberInterface
12
{
13
    private $validator;
14
15
    public function __construct(ValidatorInterface $validator)
16
    {
17
        $this->validator = $validator;
18
    }
19
20 9
    public static function getSubscribedEvents()
21
    {
22
        return [
23 9
            ['event' => 'serializer.post_deserialize', 'method' => 'onPostDeserialize'],
24 9
        ];
25
    }
26
27
    public function onPostDeserialize(ObjectEvent $event)
28
    {
29
        $context = $event->getContext();
30
31
        if ($context->getDepth() > 0) {
32
            return;
33
        }
34
35
        $groups = $context->attributes->get('groups')->getOrElse(null);
36
37
        $list = $this->validator->validate($event->getObject(), $groups);
38
39
        if ($list->count() > 0) {
40
            throw new EntityProcessingException(
41
                'Data for the entity is not valid',
42
                array_map(
43
                    function (ConstraintViolationInterface $violation) {
44
                        return $violation->getMessage();
45
                    },
46
                    iterator_to_array($list)
47
                )
48
            );
49
        }
50
    }
51
}
52