Passed
Push — master ( f7b609...3e4e55 )
by Pierre
03:01 queued 41s
created

DictionaryValidator::validate()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5.025

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