forked from geocoder-php/php-common
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAdminLevelCollection.php
More file actions
120 lines (99 loc) · 2.49 KB
/
Copy pathAdminLevelCollection.php
File metadata and controls
120 lines (99 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?php
namespace Geocoder\Model;
use Geocoder\Exception\InvalidArgument;
/**
* @author Giorgio Premi <[email protected]>
*/
final class AdminLevelCollection implements \IteratorAggregate, \Countable
{
const MAX_LEVEL_DEPTH = 5;
/**
* @var AdminLevel[]
*/
private $adminLevels;
public function __construct(array $adminLevels = [])
{
$this->adminLevels = [];
foreach ($adminLevels as $adminLevel) {
$level = $adminLevel->getLevel();
$this->checkLevel($level);
if ($this->has($level)) {
throw new InvalidArgument(sprintf("Administrative level %d is defined twice", $level));
}
$this->adminLevels[$level] = $adminLevel;
}
ksort($this->adminLevels, SORT_NUMERIC);
}
/**
* {@inheritDoc}
*/
public function getIterator()
{
return new \ArrayIterator($this->all());
}
/**
* {@inheritDoc}
*/
public function count()
{
return count($this->adminLevels);
}
/**
* @return AdminLevel|null
*/
public function first()
{
if (empty($this->adminLevels)) {
return null;
}
return reset($this->adminLevels);
}
/**
* @return AdminLevel[]
*/
public function slice($offset, $length = null)
{
return array_slice($this->adminLevels, $offset, $length, true);
}
/**
* @return bool
*/
public function has($level)
{
return isset($this->adminLevels[$level]);
}
/**
* @return AdminLevel
* @throws \OutOfBoundsException
* @throws InvalidArgument
*/
public function get($level)
{
$this->checkLevel($level);
if (! isset($this->adminLevels[$level])) {
throw new InvalidArgument(sprintf("Administrative level %d is not set for this address", $level));
}
return $this->adminLevels[$level];
}
/**
* @return AdminLevel[]
*/
public function all()
{
return $this->adminLevels;
}
/**
* @param integer $level
* @throws \OutOfBoundsException
*/
private function checkLevel($level)
{
if ($level <= 0 || $level > self::MAX_LEVEL_DEPTH) {
throw new \OutOfBoundsException(sprintf(
"Administrative level should be an integer in [1,%d], %d given",
self::MAX_LEVEL_DEPTH,
$level
));
}
}
}