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

ValidPhoneNumberValidator::validate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4.016

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 15
ccs 9
cts 10
cp 0.9
rs 9.9666
cc 4
nc 4
nop 2
crap 4.016
1
<?php
2
3
namespace Bdf\Form\Phone;
4
5
use libphonenumber\PhoneNumber as PhoneNumberValue;
6
use libphonenumber\PhoneNumberUtil;
7
use Symfony\Component\Validator\Constraint;
8
use Symfony\Component\Validator\ConstraintValidator;
9
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
10
11
/**
12
 * Validator for @see ValidPhoneNumber
13
 */
14
class ValidPhoneNumberValidator extends ConstraintValidator
15
{
16
    /**
17
     * @var PhoneNumberUtil
18
     */
19
    private $formatter;
20
21
22
    /**
23
     * PhoneNumberValidator constructor.
24
     * @param PhoneNumberUtil|null $formatter
25
     */
26 11
    public function __construct(?PhoneNumberUtil $formatter = null)
27
    {
28 11
        $this->formatter = $formatter ?? PhoneNumberUtil::getInstance();
29 11
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34 11
    public function validate($value, Constraint $constraint)
35
    {
36 11
        if (!$constraint instanceof ValidPhoneNumber) {
37
            throw new UnexpectedTypeException($constraint, ValidPhoneNumber::class);
38
        }
39
40 11
        if (!$value instanceof PhoneNumberValue) {
41 4
            return;
42
        }
43
44 9
        if (!$this->formatter->isValidNumber($value)) {
45 4
            $this->context->buildViolation($constraint->message)
46 4
                ->setParameter('{{ value }}', $this->formatValue($value))
47 4
                ->setCode(ValidPhoneNumber::INVALID_PHONE_NUMBER_ERROR)
48 4
                ->addViolation()
49
            ;
50
        }
51 9
    }
52
}
53