Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
collection.php
1<?php
2
4
5use Countable;
6use IteratorAggregate;
7use ArrayIterator;
8
9abstract class Collection implements IteratorAggregate, Countable
10{
14 protected array $collection = [];
15 protected ?\Generator $generator = null;
16
20 public function __construct(array $collection = [])
21 {
22 $this->collection = $collection;
23 }
24
28 public function getIterator(): ArrayIterator
29 {
30 return new ArrayIterator($this->collection);
31 }
32
36 public function count(): int
37 {
38 return count($this->collection);
39 }
40
45 public function add($item): Collection
46 {
47 $this->collection[] = $item;
48
49 if ($this->generator)
50 {
51 $this->generator->send($item);
52 }
53
54 return $this;
55 }
56
61 public function addItems(array $items): Collection
62 {
63
64 $this->collection = array_merge($this->collection, $items);
65
66 return $this;
67 }
68
74 public function remove($key): Collection
75 {
76 unset($this->collection[$key]);
77
78 return $this;
79 }
80
84 public function getCollection(): array
85 {
86 return $this->collection;
87 }
88
94 public function fetch()
95 {
96 if ($this->generator === null)
97 {
98 $this->generator = $this->fetchGenerator();
99 }
100
101 $item = $this->generator->current();
102 $this->generator->next();
103
104 return $item;
105 }
106
110 protected function fetchGenerator(): ?\Generator
111 {
112 if (empty($this->collection))
113 {
114 return null;
115 }
116
117 foreach ($this->collection as $key => $item)
118 {
119 yield $key => $item;
120 }
121 }
122
126 public function rewindGenerator(): void
127 {
128 if (!$this->generator->valid())
129 {
130 $this->generator->rewind();
131 }
132 }
133}
__construct(array $collection=[])