AddressCollection.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of the Geocoder package.
  5. * For the full copyright and license information, please view the LICENSE
  6. * file that was distributed with this source code.
  7. *
  8. * @license MIT License
  9. */
  10. namespace Geocoder\Model;
  11. use Geocoder\Collection;
  12. use Geocoder\Exception\CollectionIsEmpty;
  13. use Geocoder\Exception\OutOfBounds;
  14. use Geocoder\Location;
  15. use Traversable;
  16. final class AddressCollection implements Collection
  17. {
  18. /**
  19. * @var Location[]
  20. */
  21. private $locations;
  22. /**
  23. * @param Location[] $locations
  24. */
  25. public function __construct(array $locations = [])
  26. {
  27. $this->locations = array_values($locations);
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function getIterator(): Traversable
  33. {
  34. return new \ArrayIterator($this->all());
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function count(): int
  40. {
  41. return count($this->locations);
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function first(): Location
  47. {
  48. if ([] === $this->locations) {
  49. throw new CollectionIsEmpty();
  50. }
  51. return reset($this->locations);
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function isEmpty(): bool
  57. {
  58. return [] === $this->locations;
  59. }
  60. /**
  61. * @return Location[]
  62. */
  63. public function slice(int $offset, int $length = null)
  64. {
  65. return array_slice($this->locations, $offset, $length);
  66. }
  67. /**
  68. * @return bool
  69. */
  70. public function has(int $index): bool
  71. {
  72. return isset($this->locations[$index]);
  73. }
  74. /**
  75. * {@inheritdoc}
  76. */
  77. public function get(int $index): Location
  78. {
  79. if (!isset($this->locations[$index])) {
  80. throw new OutOfBounds(sprintf('The index "%s" does not exist in this collection.', $index));
  81. }
  82. return $this->locations[$index];
  83. }
  84. /**
  85. * {@inheritdoc}
  86. */
  87. public function all(): array
  88. {
  89. return $this->locations;
  90. }
  91. }