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

ValidPhoneNumberValidator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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