ClosureValidator::validate()   B
last analyzed

Complexity

Conditions 9
Paths 15

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 9.0139

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 29
ccs 17
cts 18
cp 0.9444
rs 8.0555
cc 9
nc 15
nop 2
crap 9.0139
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