Passed
Branch master (3daac1)
by Vincent
07:53
created

ClosureValidator::validate()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 8.013

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 27
ccs 16
cts 17
cp 0.9412
rs 8.4444
cc 8
nc 8
nop 2
crap 8.013
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
9
/**
10
 * Validator for @see Closure
11
 */
12
class ClosureValidator extends ConstraintValidator
13
{
14
    /**
15
     * {@inheritdoc}
16
     */
17 15
    public function validate($value, Constraint $constraint)
18
    {
19 15
        if (!$constraint instanceof Closure) {
20
            throw new UnexpectedTypeException($constraint, Closure::class);
21
        }
22
23 15
        $error = ($constraint->callback)($value, $this->context->getRoot(), $this->context);
24 15
        $code = null;
25
26 15
        if ($error === true) {
27 1
            return;
28
        }
29
30 15
        if ($error === false) {
31 1
            $error = $constraint->message;
32
        }
33
34 15
        if ($error) {
35 15
            if (is_array($error)) {
36 3
                $code = $error['code'] ?? null;
37 3
                $error = $error['message'] ?? null;
38
            }
39
40 15
            $this->context->buildViolation($error ?: $constraint->message)
41 15
                ->setParameter('{{ value }}', $this->formatValue($value))
42 15
                ->setCode($code ?: 'CUSTOM_ERROR')
43 15
                ->addViolation()
44
            ;
45
        }
46 15
    }
47
}
48