DictionaryValidator::validate()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.0342

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 8
cts 9
cp 0.8889
crap 5.0342
rs 9.6111
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
    public function __construct(private Collection $collection) {}
15
16
    public function validate(mixed $value, Constraint $constraint): void
17
    {
18
        if (!$constraint instanceof Dictionary) {
19 5
            throw new UnexpectedTypeException($constraint, Dictionary::class);
20
        }
21 5
22 5
        if (null === $value || '' === $value) {
23
            return;
24 4
        }
25
26 4
        $dictionary = $this->collection[$constraint->name];
27 1
        $values     = $dictionary->getKeys();
28
29
        if (!\in_array($value, $values, true)) {
30 3
            $this->context->addViolation(
31
                $constraint->message,
32
                [
33
                    '{{ key }}'  => $this->varToString($value),
34 3
                    '{{ keys }}' => implode(', ', array_map($this->varToString(...), $values)),
35 3
                ]
36
            );
37 3
        }
38 2
    }
39 2
40
    private function varToString(mixed $var): string
41 2
    {
42 2
        if (null === $var) {
43 2
            return 'null';
44 2
        }
45 2
46
        if (\is_string($var)) {
47
            return '"'.$var.'"';
48
        }
49
50
        if (\is_bool($var)) {
51
            return $var ? 'true' : 'false';
52 3
        }
53
54
        if (\is_float($var)) {
55
            return 0.0 === $var
0 ignored issues
show
introduced by
The condition 0.0 === $var is always false.
Loading history...
56
                ? '0.0'
57 2
                : (string) $var;
58
        }
59 2
60 1
        if (\is_object($var) && method_exists($var, '__toString')) {
61
            return (string) $var;
62
        }
63 2
64 2
        if (\is_scalar($var)) {
65
            return (string) $var;
66
        }
67 1
68 1
        throw new \Exception('Unable to transform var to string.');
69
    }
70
}
71