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

JmsValidatorSubscriber   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 13.03%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 5
dl 0
loc 41
ccs 3
cts 23
cp 0.1303
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getSubscribedEvents() 0 6 1
B onPostDeserialize() 0 24 3
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