<?php
namespace Moto\System; use Moto; use IteratorAggregate; use Countable; use ArrayAccess; use Traversable; use ArrayIterator; use Illuminate; use JsonSerializable; class BaseCollection implements IteratorAggregate, Countable, ArrayAccess, JsonSerializable { protected $_items; public function __construct($items = array()) { $this->_items = $this->_sanitizeItems($items); } protected function _sanitizeItems($items) { if (is_array($items)) { return $items; } elseif ($items instanceof self) { return $items->all(); } elseif (is_object($items) && method_exists($items, 'toArray')) { return $items->toArray(); } elseif ($items instanceof Traversable) { return iterator_to_array($items); } return (array) $items; } public function all() { return $this->_items; } public function toArray() { return array_map(function ($value) { if (is_object($value) && method_exists($value, 'toArray')) { return $value->toArray(); } elseif ($value instanceof Traversable) { $value = iterator_to_array($value); } return $value; }, $this->_items); } public function each($callback) { if (!is_callable($callback)) { return $this; } $number = 0; foreach ($this->_items as $key => $item) { if ($callback($item, $key, $number) === false) { break; } $number++; } return $this; } public function filter($callback = null) { if (is_callable($callback)) { return new static(array_filter($this->_items, $callback)); } return new static(array_filter($this->_items)); } public function get($key, $default = null) { if ($this->offsetExists($key)) { return $this->_items[$key]; } return $default; } public function has($key) { return $this->offsetExists($key); } public function push($item) { $this->offsetSet(null, $item); return $this; } public function values() { return new static(array_values($this->_items)); } public function resetKeys() { $this->_items = array_values($this->_items); return $this; } public function forget($keys) { foreach ((array) $keys as $key) { $this->offsetUnset($key); } return $this; } public function first(callable $callback = null, $default = null) { if ($callback === null) { return count($this->_items) > 0 ? reset($this->_items) : null; } foreach ($this->_items as $key => $item) { if (call_user_func($callback, $item, $key)) { return $item; } } return $default; } public function jsonSerialize() { return $this->toArray(); } public function getIterator() { return new ArrayIterator($this->_items); } public function count() { return count($this->_items); } public function offsetExists($offset) { return array_key_exists($offset, $this->_items); } public function offsetGet($offset) { return $this->_items[$offset]; } public function offsetSet($offset, $value) { if (is_null($offset)) { $this->_items[] = $value; } else { $this->_items[$offset] = $value; } } public function offsetUnset($offset) { unset($this->_items[$offset]); } } 