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

DataClassReader   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 54
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getPriority() 0 3 1
A __construct() 0 3 1
B read() 0 23 5
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