Passed
Pull Request — master (#149)
by Pierre
03:06
created

DictionaryValidator   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Test Coverage

Coverage 96.77%

Importance

Changes 7
Bugs 1 Features 0
Metric Value
eloc 29
c 7
b 1
f 0
dl 0
loc 67
ccs 30
cts 31
cp 0.9677
rs 10
wmc 13

3 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 23 5
A __construct() 0 3 1
B varToString() 0 22 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Knp\DictionaryBundle\Validator\Constraints;
6
7
use Knp\DictionaryBundle\Dictionary\Collection;
8
use Symfony\Component\Form\Exception\UnexpectedTypeException;
9
use Symfony\Component\Validator\Constraint;
10
use Symfony\Component\Validator\ConstraintValidator;
11
12
final class DictionaryValidator extends ConstraintValidator
13
{
14
    /**
15
     * @var Collection
16
     */
17
    private $dictionaries;
18
19 5
    public function __construct(Collection $dictionaries)
20
    {
21 5
        $this->dictionaries = $dictionaries;
22 5
    }
23
24 4
    public function validate($value, Constraint $constraint): void
25
    {
26 4
        if (!$constraint instanceof Dictionary) {
27 1
            throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Dictionary');
28
        }
29
30 3
        if (null === $value || '' === $value) {
31
            return;
32
        }
33
34 3
        $dictionary = $this->dictionaries[$constraint->name];
35 3
        $values     = $dictionary->getKeys();
36
37 3
        if (!\in_array($value, $values, true)) {
38 2
            $this->context->addViolation(
39 2
                $constraint->message,
40
                [
41 2
                    '{{ key }}'  => $this->varToString($value),
42 2
                    '{{ keys }}' => implode(
43 2
                        ', ',
44 2
                        array_map(
45 2
                            [$this, 'varToString'],
46
                            $values
47
                        )
48
                    ),
49
                ]
50
            );
51
        }
52 3
    }
53
54
    /**
55
     * @param mixed $var
56
     */
57 2
    private function varToString($var): string
58
    {
59 2
        if (null === $var) {
60 1
            return 'null';
61
        }
62
63 2
        if (\is_string($var)) {
64 2
            return '"'.$var.'"';
65
        }
66
67 1
        if (\is_bool($var)) {
68 1
            return $var ? 'true' : 'false';
69
        }
70
71 1
        if (\is_float($var)) {
72 1
            return 0.0 === $var
0 ignored issues
show
introduced by
The condition 0.0 === $var is always false.
Loading history...
73 1
                ? '0.0'
74 1
                : (string) $var
75
            ;
76
        }
77
78 1
        return (string) $var;
79
    }
80
}
81