|
1
|
|
|
<?php |
|
2
|
|
|
/* |
|
3
|
|
|
* This file is part of the Slince/China package. |
|
4
|
|
|
* |
|
5
|
|
|
* (c) Slince <[email protected]> |
|
6
|
|
|
* |
|
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
8
|
|
|
* file that was distributed with this source code. |
|
9
|
|
|
*/ |
|
10
|
|
|
|
|
11
|
|
|
namespace China\Region; |
|
12
|
|
|
|
|
13
|
|
|
use China\Region\Location\AddressInterface; |
|
14
|
|
|
use China\Region\Location\Area; |
|
15
|
|
|
use China\Region\Location\City; |
|
16
|
|
|
use China\Region\Location\Province; |
|
17
|
|
|
|
|
18
|
|
|
final class AddressFactory |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* 创建地区对象 |
|
22
|
|
|
* |
|
23
|
|
|
* @param array $data |
|
24
|
|
|
* @param AddressInterface $parent |
|
25
|
|
|
* |
|
26
|
|
|
* @return AddressInterface |
|
27
|
|
|
* |
|
28
|
|
|
* @throws \InvalidArgumentException |
|
29
|
|
|
*/ |
|
30
|
|
|
public static function createFromArray($data, AddressInterface $parent = null) |
|
31
|
|
|
{ |
|
32
|
|
|
if (!isset($data['type'])) { |
|
33
|
|
|
throw new \InvalidArgumentException('Missing parameter "type"'); |
|
34
|
|
|
} |
|
35
|
|
|
$address = null; |
|
36
|
|
|
switch ($data['type']) { |
|
37
|
|
|
case AddressInterface::TYPE_PROVINCE: |
|
38
|
|
|
$address = new Province($data['code'], $data['name'], $parent); |
|
39
|
|
|
break; |
|
40
|
|
|
case AddressInterface::TYPE_CITY: |
|
41
|
|
|
$address = new City($data['code'], $data['name'], $parent); |
|
42
|
|
|
break; |
|
43
|
|
|
case AddressInterface::TYPE_AREA: |
|
44
|
|
|
$address = new Area($data['code'], $data['name'], $parent); |
|
45
|
|
|
break; |
|
46
|
|
|
} |
|
47
|
|
|
if (!$address) { |
|
48
|
|
|
throw new \InvalidArgumentException(sprintf('Bad parameter "type" with "%s"', $data['type'])); |
|
49
|
|
|
} |
|
50
|
|
|
//子地区 |
|
51
|
|
|
if (isset($data['children'])) { |
|
52
|
|
|
$children = array_map(function($regionData) use ($address){ |
|
53
|
|
|
return static::createFromArray($regionData, $address); |
|
54
|
|
|
}, $data['children']); |
|
55
|
|
|
$address->setChildren(new RegionCollection($children)); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
return $address; |
|
59
|
|
|
} |
|
60
|
|
|
} |