generated from yiisoft/package-template
-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
IterableDataReader.php
302 lines (267 loc) · 8.58 KB
/
IterableDataReader.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
<?php
declare(strict_types=1);
namespace Yiisoft\Data\Reader\Iterable;
use Generator;
use InvalidArgumentException;
use RuntimeException;
use Traversable;
use Yiisoft\Arrays\ArrayHelper;
use Yiisoft\Data\Reader\DataReaderException;
use Yiisoft\Data\Reader\DataReaderInterface;
use Yiisoft\Data\Reader\FilterHandlerInterface;
use Yiisoft\Data\Reader\FilterInterface;
use Yiisoft\Data\Reader\Iterable\FilterHandler\AllHandler;
use Yiisoft\Data\Reader\Iterable\FilterHandler\AnyHandler;
use Yiisoft\Data\Reader\Iterable\FilterHandler\BetweenHandler;
use Yiisoft\Data\Reader\Iterable\FilterHandler\EqualsHandler;
use Yiisoft\Data\Reader\Iterable\FilterHandler\EqualsNullHandler;
use Yiisoft\Data\Reader\Iterable\FilterHandler\GreaterThanHandler;
use Yiisoft\Data\Reader\Iterable\FilterHandler\GreaterThanOrEqualHandler;
use Yiisoft\Data\Reader\Iterable\FilterHandler\ILikeHandler;
use Yiisoft\Data\Reader\Iterable\FilterHandler\InHandler;
use Yiisoft\Data\Reader\Iterable\FilterHandler\LessThanHandler;
use Yiisoft\Data\Reader\Iterable\FilterHandler\LessThanOrEqualHandler;
use Yiisoft\Data\Reader\Iterable\FilterHandler\LikeHandler;
use Yiisoft\Data\Reader\Iterable\FilterHandler\NotHandler;
use Yiisoft\Data\Reader\Sort;
use function array_merge;
use function count;
use function iterator_to_array;
use function sprintf;
use function uasort;
/**
* Iterable data reader takes an iterable data as a source and can:
*
* - Limit items read
* - Skip N items from the beginning
* - Sort items
* - Form a filter criteria with {@see FilterInterface}
* - Post-filter items with {@see IterableFilterHandlerInterface}
*
* @template TKey as array-key
* @template TValue as array|object
*
* @implements DataReaderInterface<TKey, TValue>
*/
final class IterableDataReader implements DataReaderInterface
{
private ?Sort $sort = null;
private ?FilterInterface $filter = null;
private int $limit = 0;
private int $offset = 0;
/**
* @psalm-var array<string, IterableFilterHandlerInterface>
*/
private array $iterableFilterHandlers = [];
/**
* @param iterable $data Data to iterate.
* @psalm-param iterable<TKey, TValue> $data
*/
public function __construct(private iterable $data)
{
$this->iterableFilterHandlers = $this->prepareFilterHandlers([
new AllHandler(),
new AnyHandler(),
new BetweenHandler(),
new EqualsHandler(),
new EqualsNullHandler(),
new GreaterThanHandler(),
new GreaterThanOrEqualHandler(),
new ILikeHandler(),
new InHandler(),
new LessThanHandler(),
new LessThanOrEqualHandler(),
new LikeHandler(),
new NotHandler(),
]);
}
/**
* @psalm-return $this
*/
public function withFilterHandlers(FilterHandlerInterface ...$filterHandlers): static
{
$new = clone $this;
$new->iterableFilterHandlers = array_merge(
$this->iterableFilterHandlers,
$this->prepareFilterHandlers($filterHandlers)
);
return $new;
}
/**
* @psalm-return $this
*/
public function withFilter(?FilterInterface $filter): static
{
$new = clone $this;
$new->filter = $filter;
return $new;
}
/**
* @psalm-return $this
*/
public function withLimit(int $limit): static
{
if ($limit < 0) {
throw new InvalidArgumentException('The limit must not be less than 0.');
}
$new = clone $this;
$new->limit = $limit;
return $new;
}
/**
* @psalm-return $this
*/
public function withOffset(int $offset): static
{
$new = clone $this;
$new->offset = $offset;
return $new;
}
/**
* @psalm-return $this
*/
public function withSort(?Sort $sort): static
{
$new = clone $this;
$new->sort = $sort;
return $new;
}
/**
* @psalm-return Generator<array-key, TValue, mixed, void>
*/
public function getIterator(): Generator
{
yield from $this->read();
}
public function getSort(): ?Sort
{
return $this->sort;
}
public function count(): int
{
return count($this->read());
}
/**
* @psalm-return array<TKey, TValue>
*/
public function read(): array
{
$data = [];
$skipped = 0;
$sortedData = $this->sort === null ? $this->data : $this->sortItems($this->data, $this->sort);
foreach ($sortedData as $key => $item) {
// Do not return more than limit items.
if ($this->limit > 0 && count($data) === $this->limit) {
/** @infection-ignore-all Here continue === break */
break;
}
// Skip offset items.
if ($skipped < $this->offset) {
++$skipped;
continue;
}
// Filter items.
if ($this->filter === null || $this->matchFilter($item, $this->filter)) {
$data[$key] = $item;
}
}
return $data;
}
public function readOne(): array|object|null
{
/** @infection-ignore-all Any value more one in `withLimit()` will be ignored because returned `current()` */
return $this
->withLimit(1)
->getIterator()
->current();
}
/**
* Return whether an item matches iterable filter.
*
* @param array|object $item Item to check.
* @param FilterInterface $filter Filter.
*
* @return bool Whether an item matches iterable filter.
*/
private function matchFilter(array|object $item, FilterInterface $filter): bool
{
$handler = $this->iterableFilterHandlers[$filter::class] ?? null;
if ($handler === null) {
throw new RuntimeException(sprintf('Filter "%s" is not supported.', $filter::class));
}
return $handler->match($item, $filter, $this->iterableFilterHandlers);
}
/**
* Sorts data items according to the given sort definition.
*
* @param iterable $items The items to be sorted.
* @param Sort $sort The sort definition.
*
* @return array The sorted items.
*
* @psalm-param iterable<TKey, TValue> $items
* @psalm-return iterable<TKey, TValue>
*/
private function sortItems(iterable $items, Sort $sort): iterable
{
$criteria = $sort->getCriteria();
if ($criteria !== []) {
$items = $this->iterableToArray($items);
/** @infection-ignore-all */
uasort(
$items,
static function (array|object $itemA, array|object $itemB) use ($criteria) {
foreach ($criteria as $key => $order) {
/** @psalm-var mixed $valueA */
$valueA = ArrayHelper::getValue($itemA, $key);
/** @psalm-var mixed $valueB */
$valueB = ArrayHelper::getValue($itemB, $key);
if ($valueB === $valueA) {
continue;
}
return ($valueA > $valueB xor $order === SORT_DESC) ? 1 : -1;
}
return 0;
}
);
}
return $items;
}
/**
* @param FilterHandlerInterface[] $filterHandlers
*
* @return IterableFilterHandlerInterface[]
* @psalm-return array<string, IterableFilterHandlerInterface>
*/
private function prepareFilterHandlers(array $filterHandlers): array
{
$result = [];
foreach ($filterHandlers as $filterHandler) {
if (!$filterHandler instanceof IterableFilterHandlerInterface) {
throw new DataReaderException(
sprintf(
'%s::withFilterHandlers() accepts instances of %s only.',
self::class,
IterableFilterHandlerInterface::class
)
);
}
$result[$filterHandler->getFilterClass()] = $filterHandler;
}
return $result;
}
/**
* Convert iterable to array.
*
* @param iterable $iterable Iterable to convert.
*
* @psalm-param iterable<TKey, TValue> $iterable
*
* @return array Resulting array.
* @psalm-return array<TKey, TValue>
*/
private function iterableToArray(iterable $iterable): array
{
return $iterable instanceof Traversable ? iterator_to_array($iterable, true) : $iterable;
}
}