-
-
Notifications
You must be signed in to change notification settings - Fork 348
Expand file tree
/
Copy pathStatement.php
More file actions
519 lines (440 loc) · 17.4 KB
/
Copy pathStatement.php
File metadata and controls
519 lines (440 loc) · 17.4 KB
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
<?php
/**
* League.Csv (https://csv.thephpleague.com)
*
* (c) Ignace Nyamagana Butera <nyamsprod@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace League\Csv;
use ArrayIterator;
use CallbackFilterIterator;
use Closure;
use Deprecated;
use Iterator;
use OutOfBoundsException;
use ReflectionException;
use ReflectionFunction;
use SortDirection;
use function array_key_exists;
use function array_reduce;
use function array_search;
use function array_values;
use function is_string;
/**
* Criteria to filter a {@link TabularData} object.
*
* @phpstan-import-type ConditionExtended from Query\PredicateCombinator
* @phpstan-import-type OrderingExtended from Query\SortCombinator
*/
class Statement
{
final protected const COLUMN_ALL = 0;
final protected const COLUMN_INCLUDE = 1;
final protected const COLUMN_EXCLUDE = 2;
/** @var array<ConditionExtended> Callables to filter the iterator. */
protected array $where = [];
/** @var array<OrderingExtended> Callables to sort the iterator. */
protected array $order_by = [];
/** iterator Offset. */
protected int $offset = 0;
/** iterator maximum length. */
protected int $limit = -1;
/** @var array<string|int> */
protected array $select = [];
/** @var self::COLUMN_* */
protected int $select_mode = self::COLUMN_ALL;
/**
* Select all the columns from the tabular data that MUST BE present in the ResultSet.
*/
public function select(string|int ...$columns): self
{
if ($columns === $this->select && self::COLUMN_INCLUDE === $this->select_mode) {
return $this;
}
$clone = clone $this;
$clone->select = $columns;
$clone->select_mode = [] === $columns ? self::COLUMN_ALL : self::COLUMN_INCLUDE;
return $clone;
}
/**
* Select all the columns from the tabular data that MUST NOT BE present in the ResultSet.
*/
public function selectAllExcept(string|int ...$columns): self
{
if ($columns === $this->select && self::COLUMN_EXCLUDE === $this->select_mode) {
return $this;
}
$clone = clone $this;
$clone->select = $columns;
$clone->select_mode = [] === $columns ? self::COLUMN_ALL : self::COLUMN_EXCLUDE;
return $clone;
}
/**
* Sets the Iterator filter method.
*
* @param callable(array, array-key): bool $where
*
* @throws ReflectionException
* @throws InvalidArgument
*/
public function where(callable $where): self
{
$where = self::wrapSingleArgumentCallable($where);
$clone = clone $this;
$clone->where[] = $where;
return $clone;
}
/**
* Sanitize the number of required parameters for a predicate.
*
* To avoid BC break in 9.16+ version the predicate should have
* at least 1 required argument.
*
* @throws InvalidArgument
* @throws ReflectionException
*
* @return ConditionExtended
*/
final protected static function wrapSingleArgumentCallable(callable $where): callable
{
if ($where instanceof Query\Predicate) {
return $where;
}
$reflection = new ReflectionFunction($where instanceof Closure ? $where : $where(...));
return match ($reflection->getNumberOfRequiredParameters()) {
0 => throw new InvalidArgument('The where condition must be callable with 2 required parameters.'),
1 => fn (mixed $record, int $key) => $where($record),
default => $where,
};
}
public function andWhere(string|int $column, Query\Constraint\Comparison|Closure|callable|string $operator, mixed $value = null): self
{
return $this->appendWhere('and', Query\Constraint\Column::filterOn($column, $operator, $value));
}
public function orWhere(string|int $column, Query\Constraint\Comparison|Closure|callable|string $operator, mixed $value = null): self
{
return $this->appendWhere('or', Query\Constraint\Column::filterOn($column, $operator, $value));
}
public function whereNot(string|int $column, Query\Constraint\Comparison|Closure|callable|string $operator, mixed $value = null): self
{
return $this->appendWhere('not', Query\Constraint\Column::filterOn($column, $operator, $value));
}
public function xorWhere(string|int $column, Query\Constraint\Comparison|Closure|callable|string $operator, mixed $value = null): self
{
return $this->appendWhere('xor', Query\Constraint\Column::filterOn($column, $operator, $value));
}
public function andWhereColumn(string|int $first, Query\Constraint\Comparison|callable|string $operator, array|int|string $second): self
{
return $this->appendWhere('and', Query\Constraint\TwoColumns::filterOn($first, $operator, $second));
}
public function orWhereColumn(string|int $first, Query\Constraint\Comparison|callable|string $operator, array|int|string $second): self
{
return $this->appendWhere('or', Query\Constraint\TwoColumns::filterOn($first, $operator, $second));
}
public function xorWhereColumn(string|int $first, Query\Constraint\Comparison|callable|string $operator, array|int|string $second): self
{
return $this->appendWhere('xor', Query\Constraint\TwoColumns::filterOn($first, $operator, $second));
}
public function whereNotColumn(string|int $first, Query\Constraint\Comparison|callable|string $operator, array|int|string $second): self
{
return $this->appendWhere('not', Query\Constraint\TwoColumns::filterOn($first, $operator, $second));
}
public function andWhereOffset(Query\Constraint\Comparison|Closure|callable|string $operator, mixed $value = null): self
{
return $this->appendWhere('and', Query\Constraint\Offset::filterOn($operator, $value));
}
public function orWhereOffset(Query\Constraint\Comparison|Closure|callable|string $operator, mixed $value = null): self
{
return $this->appendWhere('or', Query\Constraint\Offset::filterOn($operator, $value));
}
public function xorWhereOffset(Query\Constraint\Comparison|Closure|callable|string $operator, mixed $value = null): self
{
return $this->appendWhere('xor', Query\Constraint\Offset::filterOn($operator, $value));
}
public function whereNotOffset(Query\Constraint\Comparison|Closure|callable|string $operator, mixed $value = null): self
{
return $this->appendWhere('not', Query\Constraint\Offset::filterOn($operator, $value));
}
/**
* @param 'and'|'not'|'or'|'xor' $joiner
*/
final protected function appendWhere(string $joiner, Query\Predicate $predicate): self
{
if ([] === $this->where) {
return $this->where(match ($joiner) {
'and' => $predicate,
'not' => Query\Constraint\Criteria::none($predicate),
'or' => Query\Constraint\Criteria::any($predicate),
'xor' => Query\Constraint\Criteria::xany($predicate),
});
}
$predicates = Query\Constraint\Criteria::all(...$this->where);
$clone = clone $this;
$clone->where = [match ($joiner) {
'and' => $predicates->and($predicate),
'not' => $predicates->not($predicate),
'or' => $predicates->or($predicate),
'xor' => $predicates->xor($predicate),
}];
return $clone;
}
/**
* Sets an Iterator sorting callable function.
*
* @param OrderingExtended $order_by
*/
public function orderBy(callable|Query\Sort|Closure $order_by): self
{
$clone = clone $this;
$clone->order_by[] = $order_by;
return $clone;
}
/**
* Ascending ordering of the tabular data according to a column value.
*
* The column value can be modified using the callback before ordering.
*/
public function orderByAsc(string|int $column, callable|Closure|null $callback = null): self
{
return $this->orderBy(Query\Ordering\Column::sortOn($column, SortDirection::Ascending, $callback));
}
/**
* Descending ordering of the tabular data according to a column value.
*
* The column value can be modified using the callback before ordering.
*/
public function orderByDesc(string|int $column, callable|Closure|null $callback = null): self
{
return $this->orderBy(Query\Ordering\Column::sortOn($column, SortDirection::Descending, $callback));
}
/**
* Sets LimitIterator Offset.
*
* @throws Exception if the offset is less than 0
*/
public function offset(int $offset): self
{
if (0 > $offset) {
throw InvalidArgument::dueToInvalidRecordOffset($offset, __METHOD__);
}
if ($offset === $this->offset) {
return $this;
}
$clone = clone $this;
$clone->offset = $offset;
return $clone;
}
/**
* Sets LimitIterator Count.
*
* @throws Exception if the limit is less than -1
*/
public function limit(int $limit): self
{
$limit >= -1 || throw InvalidArgument::dueToInvalidLimit($limit, __METHOD__);
if ($limit === $this->limit) {
return $this;
}
$clone = clone $this;
$clone->limit = $limit;
return $clone;
}
/**
* Apply the callback if the given "condition" is (or resolves to) true.
*
* @param (callable($this): bool)|bool $condition
* @param callable($this): (self|null) $onSuccess
* @param ?callable($this): (self|null) $onFail
*/
public function when(callable|bool $condition, callable $onSuccess, ?callable $onFail = null): self
{
if (!is_bool($condition)) {
$condition = $condition($this);
}
return match (true) {
$condition => $onSuccess($this),
null !== $onFail => $onFail($this),
default => $this,
} ?? $this;
}
/**
* Executes the prepared Statement on the {@link TabularData} object.
*
* @param array<string> $header an optional header to use instead of the tabular data header
*
* @throws InvalidArgument
* @throws SyntaxError
*/
public function process(TabularData|TabularDataProvider $tabular_data, array $header = []): TabularDataReader
{
if ($tabular_data instanceof TabularDataProvider) {
$tabular_data = $tabular_data->getTabularData();
}
if ([] === $header) {
$header = $tabular_data->getHeader();
}
$iterator = $tabular_data->getRecords($header);
if ([] !== $this->where) {
$iterator = Query\Constraint\Criteria::all(...$this->where)->filter($iterator);
}
if ([] !== $this->order_by) {
$iterator = Query\Ordering\MultiSort::all(...$this->order_by)->sort($iterator);
}
if (0 !== $this->offset || -1 !== $this->limit) {
$iterator = (new Query\Limit($this->offset, $this->limit))->slice($iterator);
}
$iterator = new ResultSet($iterator, $header);
return match ($this->select_mode) {
self::COLUMN_EXCLUDE => $iterator->selectAllExcept(...$this->select),
self::COLUMN_INCLUDE => $iterator->select(...$this->select),
default => $iterator,
};
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release.
*
* @throws InvalidArgument
*
* @throws SyntaxError
* @see Statement::process()
* @deprecated Since version 9.16.0, this method no longer affects on the outcome of the class, use League\Csv\Statement::process() instead
*/
#[Deprecated(message:'this method no longer affects on the outcome of the class, use League\Csv\Statement::process() instead', since:'league/csv:9.16.0')]
protected function applySelect(Iterator $records, array $recordsHeader, array $select): TabularDataReader
{
$hasHeader = [] !== $recordsHeader;
$selectColumn = function (array $header, string|int $field) use ($recordsHeader, $hasHeader): array {
if (is_string($field)) {
$index = array_search($field, $recordsHeader, true);
if (false === $index) {
throw InvalidArgument::dueToInvalidColumnIndex($field, 'offset', __METHOD__);
}
$header[$index] = $field;
return $header;
}
if ($hasHeader && !array_key_exists($field, $recordsHeader)) {
throw InvalidArgument::dueToInvalidColumnIndex($field, 'offset', __METHOD__);
}
$header[$field] = $recordsHeader[$field] ?? $field;
return $header;
};
/** @var array<string> $header */
$header = array_reduce($select, $selectColumn, []);
$callback = function (array $record) use ($header): array {
$element = [];
$row = array_values($record);
foreach ($header as $offset => $headerName) {
$element[$headerName] = $row[$offset] ?? null;
}
return $element;
};
return new ResultSet(new MapIterator($records, $callback), $hasHeader ? $header : []);
}
/**
* Filters elements of an Iterator using a callback function.
*
* DEPRECATION WARNING! This method will be removed in the next major point release.
*
* @see Statement::applyFilter()
* @deprecated Since version 9.15.0, this method no longer affects on the outcome of the class, use League\Csv\Statement::applyFilter() instead
* @codeCoverageIgnore
*/
#[Deprecated(message:'this method no longer affects on the outcome of the class, use League\Csv\Statement::applyFilter() instead', since:'league/csv:9.15.0')]
protected function filter(Iterator $iterator, callable $callable): CallbackFilterIterator
{
return new CallbackFilterIterator($iterator, $callable);
}
/**
* Filters elements of an Iterator using a callback function.
*
* DEPRECATION WARNING! This method will be removed in the next major point release.
*
* @see Statement::process()
* @deprecated Since version 9.16.0, this method no longer affects on the outcome of the class, use League\Csv\Statement::process() instead
* @codeCoverageIgnore
*/
#[Deprecated(message:'this method no longer affects on the outcome of the class, use League\Csv\Statement::process() instead', since:'league/csv:9.16.0')]
protected function applyFilter(Iterator $iterator): Iterator
{
$filter = function (array $record, string|int $key): bool {
foreach ($this->where as $where) {
if (true !== $where($record, $key)) {
return false;
}
}
return true;
};
return new CallbackFilterIterator($iterator, $filter);
}
/**
* Sorts the Iterator.
*
* DEPRECATION WARNING! This method will be removed in the next major point release.
*
* @see Statement::process()
* @deprecated Since version 9.16.0, this method no longer affects on the outcome of the class, use League\Csv\Statement::process() instead
* @codeCoverageIgnore
*/
#[Deprecated(message:'this method no longer affects on the outcome of the class, use League\Csv\Statement::process() instead', since:'league/csv:9.16.0')]
protected function buildOrderBy(Iterator $iterator): Iterator
{
if ([] === $this->order_by) {
return $iterator;
}
$compare = function (array $record_a, array $record_b): int {
foreach ($this->order_by as $callable) {
if (0 !== ($cmp = $callable($record_a, $record_b))) {
return $cmp;
}
}
return $cmp ?? 0;
};
$class = new class () extends ArrayIterator {
public function seek(int $offset): void
{
try {
parent::seek($offset);
} catch (OutOfBoundsException) {
return;
}
}
};
/** @var ArrayIterator<array-key, array<string|null>> $it */
$it = new $class([...$iterator]);
$it->uasort($compare);
return $it;
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release.
*
* @param ?callable(array, array-key): bool $where , Deprecated argument use Statement::where instead
* @param int $offset, Deprecated argument use Statement::offset instead
* @param int $limit, Deprecated argument use Statement::limit instead
*
* @throws Exception
* @throws InvalidArgument
* @throws ReflectionException
*
* @see Statement::__construct()
* @deprecated Since version 9.22.0, use League\Csv\Statement::__construct() instead
* @codeCoverageIgnore
*/
#[Deprecated(message:'use League\Csv\Statement::__construct() instead', since:'league/csv:9.22.0')]
public static function create(?callable $where = null, int $offset = 0, int $limit = -1): self
{
$stmt = new self();
if (null !== $where) {
$stmt = $stmt->where($where);
}
if (0 !== $offset) {
$stmt = $stmt->offset($offset);
}
if (-1 !== $limit) {
$stmt = $stmt->limit($limit);
}
return $stmt;
}
}