Passed
Pull Request — master (#207)
by Pierre
02:35
created

DictionaryValidator::validate()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.0187

Importance

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