|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Created by PhpStorm. |
|
4
|
|
|
* User: Carp Cai |
|
5
|
|
|
* Date: 2018/12/1 |
|
6
|
|
|
* Time: 10:23 PM |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace CarpCai\AddressParser\Countries; |
|
10
|
|
|
|
|
11
|
|
|
use CarpCai\AddressParser\AddressStruct; |
|
12
|
|
|
|
|
13
|
|
|
class USParser extends BaseCountryParser implements iParser |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* CarpCai <2018/12/1 10:47 PM> |
|
17
|
|
|
* @param $addressString |
|
18
|
|
|
* @return AddressStruct |
|
19
|
|
|
*/ |
|
20
|
|
|
public function split($addressString) |
|
21
|
|
|
{ |
|
22
|
|
|
$addressString = "555 Test Drive, Testville, CA 98773"; |
|
23
|
|
|
|
|
24
|
|
|
preg_match("/(.+), (\w+), (\w+) (\w+)/", $addressString, $matches); |
|
25
|
|
|
|
|
26
|
|
|
list($original, $street, $city, $state, $zip) = $matches; |
|
27
|
|
|
$address = new AddressStruct([ |
|
28
|
|
|
'city' => $city, |
|
29
|
|
|
'state' => $state, |
|
30
|
|
|
'addressLine1' => $street, |
|
31
|
|
|
'zipcode' => $zip, |
|
32
|
|
|
]); |
|
33
|
|
|
$this->_checkAddress($address); |
|
34
|
|
|
|
|
35
|
|
|
return $address; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* 检查地址真实性 |
|
40
|
|
|
* Check address authenticity |
|
41
|
|
|
* CarpCai <2018/12/2 7:52 PM> |
|
42
|
|
|
*/ |
|
43
|
|
|
private function _checkAddress(&$address) |
|
44
|
|
|
{ |
|
45
|
|
|
//check state |
|
46
|
|
|
$statesMap = json_decode(file_get_contents('Json/US_states.json'), true); |
|
47
|
|
|
$state = $address->state; |
|
48
|
|
|
if(in_array($state, array_keys($statesMap))){ |
|
49
|
|
|
$address->state_text = $statesMap[$state]; |
|
50
|
|
|
}else if (in_array($state, array_values($statesMap))){ |
|
51
|
|
|
$address->state = array_flip($statesMap)[$state]; |
|
52
|
|
|
$address->state_text = $state; |
|
53
|
|
|
}else{ |
|
54
|
|
|
$this->_setError($address, 'The state does not exist'); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
//check addressLine1 |
|
58
|
|
|
list($HouseNumber) = explode(' ', $address->addressLine1); |
|
59
|
|
|
if(!is_numeric($HouseNumber)){ |
|
60
|
|
|
$this->_setError($address, 'The address must start with a number'); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
//check zipcode |
|
64
|
|
|
if(!is_numeric($address->zipcode)){ |
|
65
|
|
|
$this->_setError($address, 'the Zip code must be a number'); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
} |