ClosureValidator   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Test Coverage

Coverage 94.44%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
eloc 18
c 1
b 0
f 0
dl 0
loc 34
ccs 17
cts 18
cp 0.9444
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B validate() 0 29 9
1
<?php
2
3
namespace Bdf\Form\Constraint;
4
5
use Symfony\Component\Validator\Constraint;
6
use Symfony\Component\Validator\ConstraintValidator;
7
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
8
use WeakReference;
9
10
/**
11
 * Validator for @see Closure
12
 */
13
class ClosureValidator extends ConstraintValidator
14
{
15
    /**
16
     * {@inheritdoc}
17
     */
18 35
    public function validate($value, Constraint $constraint)
19
    {
20 35
        if (!$constraint instanceof Closure) {
21
            throw new UnexpectedTypeException($constraint, Closure::class);
22
        }
23
24 35
        $element = $this->context->getRoot() instanceof WeakReference ? $this->context->getRoot()->get() : null;
25
        /** @psalm-suppress PossiblyNullArgument */
26 35
        $error = ($constraint->callback)($value, $element, $this->context);
27 35
        $code = null;
28
29 35
        if ($error === true) {
30 2
            return;
31
        }
32
33 34
        if ($error === false) {
34 6
            $error = $constraint->message;
35
        }
36
37 34
        if ($error) {
38 33
            if (is_array($error)) {
39 3
                $code = $error['code'] ?? null;
40 3
                $error = $error['message'] ?? null;
41
            }
42
43 33
            $this->context->buildViolation($error ?: $constraint->message)
44 33
                ->setParameter('{{ value }}', $this->formatValue($value))
45 33
                ->setCode($code ?: 'CUSTOM_ERROR')
46 33
                ->addViolation()
47
            ;
48
        }
49 34
    }
50
}
51