Passed
Push — master ( 7ceee0...f31e91 )
by Benoit
02:19
created

DataClassReader::getPriority()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace JBen87\ParsleyBundle\Constraint\Reader;
4
5
use Symfony\Component\Form\FormInterface;
6
use Symfony\Component\Validator\Exception\NoSuchMetadataException;
7
use Symfony\Component\Validator\Mapping\ClassMetadata;
8
use Symfony\Component\Validator\Validator\ValidatorInterface;
9
10
class DataClassReader implements ReaderInterface
11
{
12
    /**
13
     * @var ValidatorInterface
14
     */
15
    private $validator;
16
17
    /**
18
     * @param ValidatorInterface $validator
19
     */
20 6
    public function __construct(ValidatorInterface $validator)
21
    {
22 6
        $this->validator = $validator;
23 6
    }
24
25
    /**
26
     * @inheritdoc
27
     */
28 6
    public function read(FormInterface $form): array
29
    {
30 6
        $config = $form->getRoot()->getConfig();
31 6
        if (null === $config->getDataClass()) {
32 1
            return [];
33
        }
34
35
        try {
36 5
            $metadata = $this->validator->getMetadataFor($config->getDataClass());
37 1
        } catch (NoSuchMetadataException $exception) {
38 1
            return [];
39
        }
40
41 4
        if (!$metadata instanceof ClassMetadata) {
42 1
            return [];
43
        }
44
45 3
        $constraints = [];
46 3
        foreach ($metadata->getPropertyMetadata($form->getName()) as $propertyMetadatum) {
47 2
            $constraints = array_merge($constraints, $propertyMetadatum->findConstraints($metadata->getDefaultGroup()));
48
        }
49
50 3
        return $constraints;
51
    }
52
53
    /**
54
     * DataClassReader priority should be greater than FormTypeReader priority
55
     * so that FormType constraints override entity constraints.
56
     *
57
     * @inheritdoc
58
     *
59
     * @codeCoverageIgnore
60
     */
61
    public function getPriority(): int
62
    {
63
        return 10;
64
    }
65
}
66