|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Particle. |
|
4
|
|
|
* |
|
5
|
|
|
* @link http://github.com/particle-php for the canonical source repository |
|
6
|
|
|
* @copyright Copyright (c) 2005-2015 Particle (http://particle-php.com) |
|
7
|
|
|
* @license https://github.com/particle-php/validator/blob/master/LICENSE New BSD License |
|
8
|
|
|
*/ |
|
9
|
|
|
namespace Particle\Validator\Rule; |
|
10
|
|
|
|
|
11
|
|
|
use libphonenumber\NumberParseException; |
|
12
|
|
|
use libphonenumber\PhoneNumberUtil; |
|
13
|
|
|
use Particle\Validator\Rule; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* This Rule is for validating a phone number. |
|
17
|
|
|
* |
|
18
|
|
|
* @package Particle\Validator\Rule |
|
19
|
|
|
*/ |
|
20
|
|
|
class Phone extends Rule |
|
21
|
|
|
{ |
|
22
|
|
|
/** |
|
23
|
|
|
* Constants that will be used when an invalid phone number is passed. |
|
24
|
|
|
*/ |
|
25
|
|
|
const INVALID_VALUE = 'Phone::INVALID_VALUE'; |
|
26
|
|
|
const INVALID_FORMAT = 'Phone::INVALID_FORMAT'; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* The message templates which can be returned by this validator. |
|
30
|
|
|
* |
|
31
|
|
|
* @var array |
|
32
|
|
|
*/ |
|
33
|
|
|
protected $messageTemplates = [ |
|
34
|
|
|
self::INVALID_VALUE => '{{ name }} must be a valid phone number', |
|
35
|
|
|
self::INVALID_FORMAT => '{{ name }} must have a valid phone number format', |
|
36
|
|
|
]; |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @var string |
|
40
|
|
|
*/ |
|
41
|
|
|
protected $countryCode; |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Construct the Phone validator. |
|
45
|
|
|
* |
|
46
|
|
|
* @param string $countryCode |
|
47
|
|
|
*/ |
|
48
|
13 |
|
public function __construct($countryCode) |
|
49
|
|
|
{ |
|
50
|
13 |
|
$this->countryCode = $countryCode; |
|
51
|
13 |
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Validates if $value is a valid phone number. |
|
55
|
|
|
* |
|
56
|
|
|
* @param mixed $value |
|
57
|
|
|
* @return bool |
|
58
|
|
|
*/ |
|
59
|
13 |
|
public function validate($value) |
|
60
|
|
|
{ |
|
61
|
13 |
|
$phoneUtil = PhoneNumberUtil::getInstance(); |
|
62
|
|
|
|
|
63
|
|
|
try { |
|
64
|
13 |
|
$numberProto = $phoneUtil->parse($value, $this->countryCode); |
|
65
|
10 |
|
if (!$phoneUtil->isValidNumberForRegion($numberProto, $this->countryCode)) { |
|
66
|
4 |
|
return $this->error(self::INVALID_VALUE); |
|
67
|
|
|
} |
|
68
|
9 |
|
} catch (NumberParseException $e) { |
|
69
|
3 |
|
return $this->error(self::INVALID_FORMAT); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
6 |
|
return true; |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|