ArrayCollection.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace Elgg\Structs;
  3. use Exception;
  4. /**
  5. * Uses native PHP array to implement the Collection interface.
  6. *
  7. * @package Elgg.Core
  8. * @subpackage Structs
  9. * @since 1.10
  10. *
  11. * @access private
  12. */
  13. final class ArrayCollection implements Collection {
  14. /** @var array */
  15. private $items;
  16. /**
  17. * Constructor
  18. *
  19. * @param array $items The set of items in the collection
  20. */
  21. public function __construct(array $items = array()) {
  22. $this->items = $items;
  23. }
  24. /** @inheritDoc */
  25. public function contains($item) {
  26. return in_array($item, $this->items, true);
  27. }
  28. /** @inheritDoc */
  29. public function count() {
  30. return count($this->items);
  31. }
  32. /** @inheritDoc */
  33. public function current() {
  34. return current($this->items);
  35. }
  36. /** @inheritDoc */
  37. public function filter(callable $filter) {
  38. $results = array();
  39. foreach ($this->items as $item) {
  40. if ($filter($item)) {
  41. $results[] = $item;
  42. }
  43. }
  44. return new ArrayCollection($results);
  45. }
  46. /** @inheritDoc */
  47. public function key() {
  48. return key($this->items);
  49. }
  50. /** @inheritDoc */
  51. public function map(callable $mapper) {
  52. $results = array();
  53. foreach ($this->items as $item) {
  54. $results[] = $mapper($item);
  55. }
  56. return new ArrayCollection($results);
  57. }
  58. /** @inheritDoc */
  59. public function next() {
  60. return next($this->items);
  61. }
  62. /** @inheritDoc */
  63. public function rewind() {
  64. reset($this->items);
  65. }
  66. /** @inheritDoc */
  67. public function valid() {
  68. return key($this->items) !== NULL;
  69. }
  70. }