-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathPhone.php
More file actions
91 lines (83 loc) · 2.81 KB
/
Phone.php
File metadata and controls
91 lines (83 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
namespace LVR\Phone;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class Phone implements ValidationRule
{
/**
* Validation error message
*/
protected string $message = 'Incorrect phone format for :attribute.';
/**
* Run the validation rule.
*
* @param string $attribute
* @param mixed $value
* @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail
* @return void
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (! $this->isPhone($value)) {
$fail($this->message);
}
}
/**
* Checks through all validation methods to verify it is in a
* phone number format of some type
* @param string $value The phone number to check
* @return boolean is it correct format?
*/
protected function isPhone($value)
{
return $this->isE123($value) || $this->isE164($value) || $this->isNANP($value) || $this->isDigits($value);
}
/**
* Format example 5555555555, 15555555555
* @param [type] $value [description]
* @return boolean [description]
*/
protected function isDigits($value)
{
$conditions = [];
$conditions[] = strlen($value) >= 10;
$conditions[] = strlen($value) <= 16;
$conditions[] = preg_match("/[^\d]/i", $value) === 0;
return (bool) array_product($conditions);
}
/**
* Format example +22 555 555 1234, (607) 555 1234, (022607) 555 1234
* @param $value
* @return bool
*/
protected function isE123($value)
{
return preg_match('/^(?:\((\+?\d+)?\)|\+?\d+) ?\d*(-?\d{2,3} ?){0,4}$/', $value) === 1;
}
/**
* Format example +15555555555
* @param string $value The phone number to check
* @return boolean is it correct format?
*/
protected function isE164($value)
{
$conditions = [];
$conditions[] = strpos($value, "+") === 0;
$conditions[] = strlen($value) >= 9;
$conditions[] = strlen($value) <= 16;
$conditions[] = preg_match("/[^\d+]/i", $value) === 0;
return (bool) array_product($conditions);
}
/**
* Format examples: (555) 555-5555, 1 (555) 555-5555, 1-555-555-5555, 555-555-5555, 1 555 555-5555
* https://en.wikipedia.org/wiki/National_conventions_for_writing_telephone_numbers#United_States.2C_Canada.2C_and_other_NANP_countries
* @param string $value The phone number to check
* @return boolean is it correct format?
*/
protected function isNANP($value)
{
$conditions = [];
$conditions[] = preg_match("/^(?:\+1|1)?\s?-?\(?\d{3}\)?(\s|-)?\d{3}-\d{4}$/i", $value) > 0;
return (bool) array_product($conditions);
}
}