Completed
Push — master ( 5e23d0...30cc46 )
by Carp
03:48 queued 02:15
created

USParser   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 25
dl 0
loc 53
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A split() 0 16 1
A _checkAddress() 0 23 5
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
}