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

ClosureValidator   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Test Coverage

Coverage 94.12%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 17
c 1
b 0
f 0
dl 0
loc 32
ccs 16
cts 17
cp 0.9412
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B validate() 0 27 8
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