Completed
Pull Request — master (#18)
by Pavel
27:07
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.125

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 6
cp 0.5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 0
crap 1.125
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\Validator\ValidatorInterface;
9
10
final class JmsValidatorSubscriber implements EventSubscriberInterface
11
{
12
    private $validator;
13
14
    public function __construct(ValidatorInterface $validator)
15
    {
16
        $this->validator = $validator;
17
    }
18
19 12
    public static function getSubscribedEvents()
20
    {
21
        return [
22 12
            ['event' => 'serializer.post_deserialize', 'method' => 'onPostDeserialize'],
23 12
        ];
24
    }
25
26
    public function onPostDeserialize(ObjectEvent $event)
27
    {
28
        $context = $event->getContext();
29
30
        if ($context->getDepth() > 0) {
31
            return;
32
        }
33
34
        $groups = $context->attributes->get('groups')->getOrElse(null);
35
36
        $list = $this->validator->validate($event->getObject(), $groups);
37
38
        if ($list->count() > 0) {
39
            throw EntityProcessingException::fromViolationList($list);
40
        }
41
    }
42
}
43