1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace VasilDakov\Postcode; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Class Validator |
7
|
|
|
* @author Vasil Dakov <[email protected]> |
8
|
|
|
*/ |
9
|
|
|
class Validator implements ValidatorInterface |
10
|
|
|
{ |
11
|
|
|
private $code; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Two-letter country codes defined in ISO 3166-1 |
15
|
|
|
* |
16
|
|
|
* @var array<ISO 3166-1> |
17
|
|
|
*/ |
18
|
|
|
protected static $codes = [ |
19
|
|
|
'BE', 'BG', 'CA', 'DE', 'DK', 'ES', 'FR', 'IT', |
20
|
|
|
'JP', 'MT', 'NL', 'US', 'SE', 'UK', 'US' |
21
|
|
|
]; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Postcode regexes by country code |
25
|
|
|
* |
26
|
|
|
* @var array |
27
|
|
|
*/ |
28
|
|
|
protected static $regexes = [ |
29
|
|
|
'BE' => '[1-9]{1}[0-9]{3}', |
30
|
|
|
'BG' => '\d{4}', |
31
|
|
|
'CA' => '([A-Z]\d[A-Z]\s\d[A-Z]\d)', |
32
|
|
|
'DE' => '\b((?:0[1-46-9]\d{3})|(?:[1-357-9]\d{4})|(?:[4][0-24-9]\d{3})|(?:[6][013-9]\d{3}))\b', |
33
|
|
|
'DK' => '([D-d][K-k])?( |-)?[1-9]{1}[0-9]{3}', |
34
|
|
|
'ES' => '([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}', |
35
|
|
|
'FR' => '(F-)?((2[A|B])|[0-9]{2})[0-9]{3}$', |
36
|
|
|
'IT' => '(V-|I-)?[0-9]{5}', |
37
|
|
|
'JP' => '\d{3}-\d{4}', |
38
|
|
|
'MT' => '([A-Z]{3}\d{2}\d?)', |
39
|
|
|
'NL' => '[1-9][0-9]{3} ?(?!sa|sd|ss)[A-Za-z]{2}', |
40
|
|
|
'SE' => '(s-|S-){0,1}[0-9]{3}\s?[0-9]{2}', |
41
|
|
|
'UK' => '([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2}) |
42
|
|
|
|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})', |
43
|
|
|
'US' => 'd{5}\p{Punct}?\s?(?:\d{4})?', |
44
|
|
|
]; |
45
|
|
|
|
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Constructor |
49
|
|
|
* |
50
|
|
|
* @param string $code Country code ISO 3166-1 |
51
|
|
|
*/ |
52
|
3 |
|
public function __construct($code) |
53
|
|
|
{ |
54
|
3 |
|
if (!array_key_exists($code, static::$regexes)) { |
55
|
2 |
|
throw new \InvalidArgumentException( |
56
|
2 |
|
"Country code '{$code}' invalid by ISO 3166-1 or not supported" |
57
|
2 |
|
); |
58
|
|
|
} |
59
|
|
|
|
60
|
1 |
|
$this->code = $code; |
61
|
1 |
|
} |
62
|
|
|
|
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Returns true if $value is a valid postcode |
66
|
|
|
* |
67
|
|
|
* @param string $value |
68
|
|
|
* @return boolean |
69
|
|
|
*/ |
70
|
54 |
|
public function isValid($value) |
71
|
|
|
{ |
72
|
54 |
|
if (!preg_match('/^' . static::$regexes[$this->code] . '$/', $value)) { |
73
|
8 |
|
return false; |
74
|
|
|
} |
75
|
|
|
|
76
|
46 |
|
return true; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|