1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Shared Kernel library. |
5
|
|
|
* |
6
|
|
|
* Copyright (c) 2016-present LIN3S <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace LIN3S\SharedKernel\Domain\Model\Phone; |
13
|
|
|
|
14
|
|
|
use libphonenumber\NumberParseException; |
15
|
|
|
use libphonenumber\PhoneNumberFormat; |
16
|
|
|
use libphonenumber\PhoneNumberUtil; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @author Beñat Espiña <[email protected]> |
20
|
|
|
*/ |
21
|
|
|
class Phone |
|
|
|
|
22
|
|
|
{ |
23
|
|
|
private $phone; |
24
|
|
|
|
25
|
|
|
public static function fromInternatinal($phone) |
26
|
|
|
{ |
27
|
|
|
return new self($phone); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public static function fromRegion($region, $phone) |
31
|
|
|
{ |
32
|
|
|
return new self($phone, $region); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public static function fromSpain($phone) |
36
|
|
|
{ |
37
|
|
|
return new self($phone, 'ES'); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
private function __construct($phone, $region = null) |
41
|
|
|
{ |
42
|
|
|
$this->setPhone($phone, $region); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function equals(Phone $phone) |
46
|
|
|
{ |
47
|
|
|
return $this->phone->phone() === $phone->phone(); |
|
|
|
|
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function phone() |
51
|
|
|
{ |
52
|
|
|
return PhoneNumberUtil::getInstance()->format($this->phone, PhoneNumberFormat::E164); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function phoneCallingFrom($region) |
|
|
|
|
56
|
|
|
{ |
57
|
|
|
return PhoneNumberUtil::getInstance()->formatOutOfCountryCallingNumber($this->phoneNumber, $regionCode); |
|
|
|
|
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function __toString() |
61
|
|
|
{ |
62
|
|
|
return (string) $this->phone(); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
private function setPhone($phone, $region = null) |
66
|
|
|
{ |
67
|
|
|
try { |
68
|
|
|
$this->phone = PhoneNumberUtil::getInstance()->parse($phone, $region); |
69
|
|
|
$this->checkIsValidNumber($this->phone); |
70
|
|
|
} catch (NumberParseException $exception) { |
71
|
|
|
throw new PhoneInvalidFormatException( |
72
|
|
|
$exception->getMessage() |
73
|
|
|
); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
private function checkIsValidNumber($phone, $region = null) |
|
|
|
|
78
|
|
|
{ |
79
|
|
|
if (!PhoneNumberUtil::getInstance()->isValidNumber($this->phone)) { |
80
|
|
|
throw new PhoneInvalidFormatException(); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|