PhoneNumberValidator   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 3
dl 0
loc 31
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A validate() 0 12 3
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Explicit Architecture POC,
7
 * which is created on top of the Symfony Demo application.
8
 *
9
 * (c) Herberto Graça <[email protected]>
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace Acme\App\Infrastructure\Validation\PhoneNumber\LibPhoneNumber;
16
17
use Acme\App\Core\Port\Validation\PhoneNumber\PhoneNumberCouldNotBeParsedException;
18
use Acme\App\Core\Port\Validation\PhoneNumber\PhoneNumberInvalidException;
19
use Acme\App\Core\Port\Validation\PhoneNumber\PhoneNumberValidatorInterface;
20
use libphonenumber\NumberParseException;
21
use libphonenumber\PhoneNumberUtil;
22
23
final class PhoneNumberValidator implements PhoneNumberValidatorInterface
24
{
25
    /**
26
     * @var PhoneNumberUtil
27
     */
28
    private $phoneNumberUtil;
29
30
    /**
31
     * @var string
32
     */
33
    private $countryCode;
34
35
    public function __construct(PhoneNumberUtil $phoneNumberUtil, string $countryCode)
36
    {
37
        $this->phoneNumberUtil = $phoneNumberUtil;
38
        $this->countryCode = $countryCode;
39
    }
40
41
    public function validate(string $phoneNumber, string $countryCode = null): void
42
    {
43
        try {
44
            $number = $this->phoneNumberUtil->parse($phoneNumber, $countryCode ?? $this->countryCode);
45
        } catch (NumberParseException $exception) {
46
            throw new PhoneNumberCouldNotBeParsedException($phoneNumber);
47
        }
48
49
        if (!$this->phoneNumberUtil->isValidNumber($number)) {
50
            throw new PhoneNumberInvalidException($phoneNumber);
51
        }
52
    }
53
}
54