123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139 |
- <?php
- declare(strict_types=1);
- namespace Geocoder\Model;
- use Geocoder\Exception\CollectionIsEmpty;
- use Geocoder\Exception\InvalidArgument;
- use Geocoder\Exception\OutOfBounds;
- use Traversable;
- final class AdminLevelCollection implements \IteratorAggregate, \Countable
- {
- const MAX_LEVEL_DEPTH = 5;
-
- 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);
- }
-
- public function getIterator(): Traversable
- {
- return new \ArrayIterator($this->all());
- }
-
- public function count(): int
- {
- return count($this->adminLevels);
- }
-
- public function first(): AdminLevel
- {
- if ([] === $this->adminLevels) {
- throw new CollectionIsEmpty();
- }
- return reset($this->adminLevels);
- }
-
- public function slice(int $offset, int $length = null): array
- {
- return array_slice($this->adminLevels, $offset, $length, true);
- }
-
- public function has(int $level): bool
- {
- return isset($this->adminLevels[$level]);
- }
-
- public function get(int $level): AdminLevel
- {
- $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];
- }
-
- public function all(): array
- {
- return $this->adminLevels;
- }
-
- private function checkLevel(int $level)
- {
- if ($level <= 0 || $level > self::MAX_LEVEL_DEPTH) {
- throw new OutOfBounds(sprintf('Administrative level should be an integer in [1,%d], %d given', self::MAX_LEVEL_DEPTH, $level));
- }
- }
- }
|