USParser::split()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 14
rs 9.9666
c 0
b 0
f 0
cc 1
nc 1
nop 1
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
        preg_match("/(.+),(.+),([A-Za-z_ ]+)(\d+)/", $addressString, $matches);
23
24
        list($original, $street, $city, $state, $zipcode) = $matches;
25
        $address = new AddressStruct([
26
            'city'         => trim($city),
27
            'state'        => trim($state),
28
            'addressLine1' => trim($street),
29
            'zipcode'      => trim($zipcode),
30
        ]);
31
        $this->_checkAddress($address);
32
33
        return $address;
34
    }
35
36
    /**
37
     * 检查地址真实性
38
     * Check address authenticity
39
     * CarpCai <2018/12/2 7:52 PM>
40
     */
41
    private function _checkAddress(&$address)
42
    {
43
        //check state
44
        $statesMap = json_decode(file_get_contents(__DIR__ . '/../Json/US_states.json'), true);
45
        $state = $address->state;
46
        if(in_array($state, array_keys($statesMap))){
47
            $address->state_text = $statesMap[$state];
48
        }else if (in_array($state, array_values($statesMap))){
49
            $address->state = array_flip($statesMap)[$state];
50
            $address->state_text = $state;
51
        }else{
52
            $this->_setError($address, 'The state does not exist');
53
        }
54
55
        //check addressLine1
56
        list($HouseNumber) = explode(' ', $address->addressLine1);
57
        if(!is_numeric($HouseNumber)){
58
            $this->_setError($address, 'The address must start with a number');
59
        }
60
61
        //check zipcode
62
        if(!is_numeric($address->zipcode)){
63
            $this->_setError($address, 'the Zip code must be a number');
64
        }
65
    }
66
}