| 1 | <?php |
||
| 7 | abstract class ModelCollection implements CreatableFromArray, \Countable, \Iterator |
||
| 8 | { |
||
| 9 | /** |
||
| 10 | * @var array |
||
| 11 | */ |
||
| 12 | protected $items = []; |
||
| 13 | |||
| 14 | /** |
||
| 15 | * Current iterator key. |
||
| 16 | * |
||
| 17 | * @var int |
||
| 18 | */ |
||
| 19 | protected $key = 0; |
||
| 20 | |||
| 21 | 8 | protected function __construct() |
|
| 22 | { |
||
| 23 | 8 | } |
|
| 24 | |||
| 25 | /** |
||
| 26 | * {@inheritdoc} |
||
| 27 | */ |
||
| 28 | 5 | public static function createFromArray(array $data) |
|
| 29 | { |
||
| 30 | 5 | $collection = new static(); |
|
| 31 | 5 | foreach ($data as $itemData) { |
|
| 32 | 5 | $collection->items[] = $collection->createItem($itemData); |
|
| 33 | } |
||
| 34 | |||
| 35 | 5 | return $collection; |
|
| 36 | } |
||
| 37 | |||
| 38 | /** |
||
| 39 | * @return array |
||
| 40 | */ |
||
| 41 | 2 | public function getItems() |
|
| 42 | { |
||
| 43 | 2 | return $this->items; |
|
| 44 | } |
||
| 45 | |||
| 46 | /** |
||
| 47 | * {@inheritdoc} |
||
| 48 | */ |
||
| 49 | 8 | public function count() |
|
| 50 | { |
||
| 51 | 8 | return count($this->items); |
|
| 52 | } |
||
| 53 | |||
| 54 | /** |
||
| 55 | * {@inheritdoc} |
||
| 56 | */ |
||
| 57 | 1 | public function key() |
|
| 58 | { |
||
| 59 | 1 | return $this->key; |
|
| 60 | } |
||
| 61 | |||
| 62 | /** |
||
| 63 | * {@inheritdoc} |
||
| 64 | */ |
||
| 65 | 4 | public function next() |
|
| 66 | { |
||
| 67 | 4 | ++$this->key; |
|
| 68 | 4 | } |
|
| 69 | |||
| 70 | /** |
||
| 71 | * @return bool |
||
| 72 | */ |
||
| 73 | 1 | public function valid() |
|
| 74 | { |
||
| 75 | 1 | return $this->key < $this->count(); |
|
| 76 | } |
||
| 77 | |||
| 78 | /** |
||
| 79 | * {@inheritdoc} |
||
| 80 | */ |
||
| 81 | 5 | public function current() |
|
| 82 | { |
||
| 83 | 5 | return $this->items[$this->key]; |
|
| 84 | } |
||
| 85 | |||
| 86 | /** |
||
| 87 | * {@inheritdoc} |
||
| 88 | */ |
||
| 89 | 2 | public function rewind() |
|
| 90 | { |
||
| 91 | 2 | $this->key = 0; |
|
| 92 | 2 | } |
|
| 93 | |||
| 94 | /** |
||
| 95 | * @param array $data |
||
| 96 | */ |
||
| 97 | abstract protected function createItem(array $data); |
||
| 98 | } |
||
| 99 |