Repository navigation
Expand file tree
/
Copy pathArrayMultiQuerySortTrait.php
More file actions
1323 lines (1137 loc) · 38.1 KB
/
Copy pathArrayMultiQuerySortTrait.php
File metadata and controls
1323 lines (1137 loc) · 38.1 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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace Infocyph\ArrayKit\Array\Concerns;
use Infocyph\ArrayKit\Array\ArraySharedOps;
use Infocyph\ArrayKit\Array\ArraySingle;
use Infocyph\ArrayKit\Array\ArraySingleOps;
use Infocyph\ArrayKit\Array\ArrayValueSetOps;
use InvalidArgumentException;
use function Infocyph\ArrayKit\compare;
/** @internal */
trait ArrayMultiQuerySortTrait
{
private const int ROW_MEMBERSHIP_LOOKUP_MIN_VALUES = 256;
/**
* Filter a 2D array by a single key's comparison (like "where 'age' between 18 and 65").
*
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function between(array $array, string $key, float|int $from, float|int $to): array
{
$results = [];
foreach ($array as $index => $item) {
if (
is_array($item)
&& ArraySingle::exists($item, $key)
&& compare($item[$key], $from, '>=')
&& compare($item[$key], $to, '<=')
) {
$results[$index] = $item;
}
}
return $results;
}
/**
* Count rows grouped by key/callback buckets.
*
* @param array<array-key, mixed> $array
* @return array<int|string, int>
*/
public static function countBy(array $array, string|callable $groupBy): array
{
$counts = [];
$useCallback = !is_string($groupBy);
foreach ($array as $key => $row) {
if (!$useCallback && (!is_array($row) || !array_key_exists($groupBy, $row))) {
continue;
}
$bucket = $useCallback ? $groupBy($row, $key) : $row[$groupBy];
$arrayKey = self::requireArrayKey($bucket, 'countBy');
$counts[$arrayKey] = ($counts[$arrayKey] ?? 0) + 1;
}
return $counts;
}
/**
* Return duplicate rows by derived key (first duplicate occurrence onward).
*
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function duplicatesBy(array $array, string|callable $keyOrCallback, bool $strict = false): array
{
return self::collectByDerivedKey($array, $keyOrCallback, $strict, keepDuplicates: true);
}
/**
* Return the first row where the key comparison matches.
*
* @param array<array-key, mixed> $array
*/
public static function firstWhere(
array $array,
string $key,
mixed $operator = null,
mixed $value = null,
mixed $default = null,
): mixed {
if (func_num_args() === 3) {
$value = $operator;
$operator = null;
}
$operator = is_string($operator) ? $operator : null;
foreach ($array as $row) {
if (
is_array($row)
&& ArraySingle::exists($row, $key)
&& compare($row[$key], $value, $operator)
) {
return $row;
}
}
return $default;
}
/**
* Return the first row where a key value is in the given value set.
*
* @param array<array-key, mixed> $array
* @param array<array-key, mixed> $values
*/
public static function firstWhereIn(array $array, string $key, array $values, bool $strict = false, mixed $default = null): mixed
{
$lookup = self::buildInLookup($values, $strict);
if ($lookup === null) {
return self::firstWhereInByScan($array, $key, $values, $strict, $default);
}
foreach ($array as $row) {
if (!is_array($row) || !array_key_exists($key, $row)) {
continue;
}
if (self::rowLookupContains($lookup, $values, $row[$key], $strict)) {
return $row;
}
}
return $default;
}
/**
* Group a 2D array by a given column or callback.
*
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function groupBy(array $array, string|callable $groupBy, bool $preserveKeys = false): array
{
$results = [];
$useCallback = !is_string($groupBy);
foreach ($array as $key => $row) {
if (!$useCallback && (!is_array($row) || !array_key_exists($groupBy, $row))) {
continue;
}
$resolved = $useCallback ? $groupBy($row, $key) : $row[$groupBy];
$groupKey = self::requireArrayKey($resolved, 'groupBy');
if ($preserveKeys) {
$results[$groupKey][$key] = $row;
} else {
$results[$groupKey][] = $row;
}
}
return $results;
}
/**
* Alias of keyBy().
*
* @param array<array-key, mixed> $array
* @return array<int|string, mixed>
*/
public static function indexBy(array $array, string|callable $indexBy): array
{
return static::keyBy($array, $indexBy);
}
/**
* Key rows by a derived key (last write wins on duplicate keys).
*
* @param array<array-key, mixed> $array
* @return array<int|string, mixed>
*/
public static function keyBy(array $array, string|callable $keyBy): array
{
$results = [];
$useCallback = !is_string($keyBy);
foreach ($array as $index => $row) {
if (!$useCallback && (!is_array($row) || !array_key_exists($keyBy, $row))) {
continue;
}
$resolved = $useCallback ? $keyBy($row, $index) : $row[$keyBy];
$results[self::requireArrayKey($resolved, 'keyBy')] = $row;
}
return $results;
}
/**
* Return the last item in a 2D array or single-dim array, depending on usage.
*
* @param array<array-key, mixed> $array
*/
public static function last(array $array, ?callable $callback = null, mixed $default = null): mixed
{
if ($callback === null) {
return empty($array) ? $default : end($array);
}
$resolved = $default;
foreach ($array as $key => $row) {
if ($callback($row, $key)) {
$resolved = $row;
}
}
return $resolved;
}
/**
* Transform rows and return a key/value map from callback results.
*
* Callback must return a one-item array like [newKey => newValue].
*
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function mapWithKeys(array $array, callable $callback): array
{
$results = [];
foreach ($array as $key => $row) {
$mapped = $callback($row, $key);
if (!is_array($mapped)) {
continue;
}
foreach ($mapped as $mappedKey => $mappedValue) {
$results[$mappedKey] = $mappedValue;
}
}
return $results;
}
/**
* Return the maximum numeric row value by key/callback.
*
* @param array<array-key, mixed> $array
*/
public static function max(array $array, string|callable $keyOrCallback): float|int|null
{
return self::formatNumericResult(
self::selectExtremeValue($array, $keyOrCallback, pickMax: true),
);
}
/**
* Return the row with the largest numeric score by key/callback.
*
* @param array<array-key, mixed> $array
*/
public static function maxBy(array $array, string|callable $keyOrCallback): mixed
{
return self::selectExtremeRow($array, $keyOrCallback, pickMax: true);
}
/**
* Return the minimum numeric row value by key/callback.
*
* @param array<array-key, mixed> $array
*/
public static function min(array $array, string|callable $keyOrCallback): float|int|null
{
return self::formatNumericResult(
self::selectExtremeValue($array, $keyOrCallback, pickMax: false),
);
}
/**
* Return the row with the smallest numeric score by key/callback.
*
* @param array<array-key, mixed> $array
*/
public static function minBy(array $array, string|callable $keyOrCallback): mixed
{
return self::selectExtremeRow($array, $keyOrCallback, pickMax: false);
}
/**
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function pluck(array $array, string $column, ?string $indexBy = null): array
{
$results = [];
foreach ($array as $row) {
if (!is_array($row) || !array_key_exists($column, $row)) {
continue;
}
$value = $row[$column];
if ($indexBy === null) {
$results[] = $value;
continue;
}
if (array_key_exists($indexBy, $row)) {
$results[self::requireArrayKey($row[$indexBy], 'pluck')] = $value;
}
}
return $results;
}
/**
* Return an array with all values that do not pass the given callback.
*
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function reject(array $array, mixed $callback = true): array
{
$results = [];
if (!is_string($callback) && is_callable($callback)) {
foreach ($array as $key => $row) {
if (!$callback($row, $key)) {
$results[$key] = $row;
}
}
return $results;
}
foreach ($array as $key => $row) {
if ($row != $callback) {
$results[$key] = $row;
}
}
return $results;
}
/**
* Check if the array (of rows) contains at least one row matching a condition.
*
* @param array<array-key, mixed> $array
*/
public static function some(array $array, callable $callback): bool
{
return array_any($array, $callback);
}
/**
* Sort a 2D array by a specified column or using a callback function.
*
* Callback receives ($row, $key).
*
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function sortBy(
array $array,
string|callable $by,
bool $desc = false,
int $options = \SORT_REGULAR,
): array {
if (!is_string($by)) {
$scores = [];
foreach ($array as $key => $row) {
$scores[$key] = self::invokeRowCallback($by, $row, $key);
}
uksort(
$array,
static function (int|string $leftKey, int|string $rightKey) use ($scores, $desc, $options): int {
$comparison = self::compareSortValues(
$scores[$leftKey] ?? null,
$scores[$rightKey] ?? null,
$options,
);
return self::applySortDirection($comparison, $desc);
},
);
return $array;
}
uasort($array, function ($a, $b) use ($by, $desc, $options) {
$valA = is_array($a) ? ($a[$by] ?? null) : null;
$valB = is_array($b) ? ($b[$by] ?? null) : null;
return self::applySortDirection(
self::compareSortValues($valA, $valB, $options),
$desc,
);
});
return $array;
}
/**
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function sortByDesc(array $array, string|callable $by, int $options = \SORT_REGULAR): array
{
return static::sortBy($array, $by, true, $options);
}
/**
* Sort by multiple sort rules.
*
* Each criterion can be:
* - ['column', 'asc'|'desc', SORT_*]
* - [callable, 'asc'|'desc', SORT_*]
*
* @param array<array-key, mixed> $array
* @param array<int, array<int, mixed>> $criteria
* @return array<array-key, mixed>
*/
public static function sortByMany(array $array, array $criteria): array
{
if ($criteria === []) {
return $array;
}
$prepared = self::prepareSortByManyCriteria($array, $criteria);
uksort(
$array,
static fn(int|string $leftKey, int|string $rightKey): int => self::compareByManyCriteria(
$leftKey,
$rightKey,
$prepared,
),
);
return $array;
}
/**
* Recursively sort a multidimensional array by keys/values.
*
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function sortRecursive(array $array, int $options = \SORT_REGULAR, bool $descending = false): array
{
foreach ($array as &$value) {
if (is_array($value)) {
$value = static::sortRecursive($value, $options, $descending);
}
}
unset($value);
if (ArraySingle::isAssoc($array)) {
$descending
? krsort($array, $options)
: ksort($array, $options);
} else {
usort(
$array,
static fn(mixed $left, mixed $right): int => $descending
? -self::compareSortValues($left, $right, $options)
: self::compareSortValues($left, $right, $options),
);
}
return $array;
}
/**
* Safe recursive sort with depth/node guards.
*
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function sortRecursiveGuarded(
array $array,
int $options = \SORT_REGULAR,
bool $descending = false,
int $maxDepth = 256,
int $maxNodes = 100000,
bool $throwOnTooDeep = false,
): array {
$visitedNodes = 0;
$complete = true;
return self::sortRecursiveWithGuards(
$array,
$options,
$descending,
1,
$visitedNodes,
$maxDepth,
$maxNodes,
$throwOnTooDeep,
$complete,
);
}
/**
* Calculate the sum of an array of values.
*
* Callback receives ($row, $key). Non-numeric values are ignored.
*
* @param array<array-key, mixed> $array
*/
public static function sum(array $array, string|callable|null $keyOrCallback = null): float|int
{
$total = 0;
foreach ($array as $key => $row) {
$total += self::extractSummableValue($row, $keyOrCallback, $key);
}
return $total;
}
/**
* Return unique rows by derived key.
*
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function uniqueBy(array $array, string|callable $keyOrCallback, bool $strict = false): array
{
return self::collectByDerivedKey($array, $keyOrCallback, $strict, keepDuplicates: false);
}
/**
* Filter a 2D array by a single key's comparison (like "where 'age' > 18").
*
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function where(array $array, string $key, mixed $operator = null, mixed $value = null): array
{
if (func_num_args() === 3) {
$value = $operator;
$operator = null;
}
$operator = is_string($operator) ? $operator : null;
$results = [];
foreach ($array as $index => $item) {
if (
is_array($item)
&& ArraySingle::exists($item, $key)
&& compare($item[$key], $value, $operator)
) {
$results[$index] = $item;
}
}
return $results;
}
/**
* Filter rows where a key value falls inside an inclusive range.
*
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function whereBetween(array $array, string $key, float|int $from, float|int $to): array
{
return self::between($array, $key, $from, $to);
}
/**
* Filter a 2D array by a custom callback function on each row.
*
* @param array<array-key, mixed> $array
*/
public static function whereCallback(array $array, ?callable $callback = null, mixed $default = null): mixed
{
if ($callback === null) {
return empty($array) ? $default : $array;
}
$results = [];
foreach ($array as $index => $item) {
if ((bool) $callback($item, $index)) {
$results[$index] = $item;
}
}
return $results;
}
/**
* Filter rows where a key value contains a given substring.
*
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function whereContains(array $array, string $key, string $needle, bool $caseSensitive = true): array
{
$match = $caseSensitive ? $needle : strtolower($needle);
return self::filterByTextMatch(
$array,
$key,
static fn(string $text): bool => str_contains($caseSensitive ? $text : strtolower($text), $match),
);
}
/**
* Filter rows where a key value ends with a given suffix.
*
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function whereEndsWith(array $array, string $key, string $suffix, bool $caseSensitive = true): array
{
$needle = $caseSensitive ? $suffix : strtolower($suffix);
return self::filterByTextMatch(
$array,
$key,
static fn(string $text): bool => str_ends_with($caseSensitive ? $text : strtolower($text), $needle),
);
}
/**
* Filter rows where "column" matches one of the given values.
*
* @param array<array-key, mixed> $array
* @param array<array-key, mixed> $values
* @return array<array-key, mixed>
*/
public static function whereIn(array $array, string $key, array $values, bool $strict = false): array
{
$results = [];
$lookup = self::buildInLookup($values, $strict);
if ($lookup === null) {
return self::whereInByScan($array, $key, $values, $strict, true);
}
foreach ($array as $index => $row) {
if (!is_array($row) || !array_key_exists($key, $row)) {
continue;
}
if (self::rowLookupContains($lookup, $values, $row[$key], $strict)) {
$results[$index] = $row;
}
}
return $results;
}
/**
* Filter rows where a key value matches an SQL-like pattern ('%' and '_').
*
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function whereLike(array $array, string $key, string $pattern, bool $caseSensitive = false): array
{
$quoted = preg_quote($pattern, '/');
$regex = '/\\A' . str_replace(['%', '_'], ['.*', '.'], $quoted) . '\\z/s' . ($caseSensitive ? '' : 'i');
$results = [];
foreach ($array as $index => $row) {
if (!is_array($row) || !array_key_exists($key, $row)) {
continue;
}
$value = $row[$key];
if (!is_scalar($value) && $value !== null) {
continue;
}
$matched = preg_match($regex, (string) $value);
if ($matched === false) {
throw new \RuntimeException('SQL-like pattern matching failed: ' . preg_last_error_msg());
}
if ($matched === 1) {
$results[$index] = $row;
}
}
return $results;
}
/**
* Filter rows where "column" does NOT match one of the given values.
*
* @param array<array-key, mixed> $array
* @param array<array-key, mixed> $values
* @return array<array-key, mixed>
*/
public static function whereNotIn(array $array, string $key, array $values, bool $strict = false): array
{
$results = [];
$lookup = self::buildInLookup($values, $strict);
if ($lookup === null) {
return self::whereInByScan($array, $key, $values, $strict, false);
}
foreach ($array as $index => $row) {
if (!is_array($row) || !array_key_exists($key, $row)) {
$results[$index] = $row;
continue;
}
if (!self::rowLookupContains($lookup, $values, $row[$key], $strict)) {
$results[$index] = $row;
}
}
return $results;
}
/**
* Filter rows where a column is not null.
*
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function whereNotNull(array $array, string $key): array
{
return self::filterByNullState($array, $key, expectNull: false);
}
/**
* Filter rows where a column is null.
*
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function whereNull(array $array, string $key): array
{
return self::filterByNullState($array, $key, expectNull: true);
}
/**
* Filter rows where a key value starts with a given prefix.
*
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
public static function whereStartsWith(array $array, string $key, string $prefix, bool $caseSensitive = true): array
{
$needle = $caseSensitive ? $prefix : strtolower($prefix);
return self::filterByTextMatch(
$array,
$key,
static fn(string $text): bool => str_starts_with($caseSensitive ? $text : strtolower($text), $needle),
);
}
private static function applySortDirection(int $comparison, bool $desc): int
{
return $desc ? -$comparison : $comparison;
}
private static function asNumeric(mixed $value): float|int
{
return ArraySingleOps::numericValue($value) ?? 0;
}
private static function asString(mixed $value): string
{
return ArraySharedOps::asString($value);
}
/**
* @param array<array-key, mixed> $values
* @return array<string, bool>|null
*/
private static function buildInLookup(array $values, bool $strict): ?array
{
if (count($values) < self::ROW_MEMBERSHIP_LOOKUP_MIN_VALUES) {
return null;
}
if ($strict) {
return ArrayValueSetOps::strictLookup($values);
}
$lookup = ['type:non-numeric-string' => true];
foreach ($values as $value) {
if (!is_string($value) || is_numeric($value)) {
return null;
}
$lookup['value:' . strlen($value) . ':' . $value] = true;
}
return $lookup;
}
/**
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
private static function collectByDerivedKey(
array $array,
string|callable $keyOrCallback,
bool $strict,
bool $keepDuplicates,
): array {
if (!$strict) {
return self::collectByDerivedKeyLoose($array, $keyOrCallback, $keepDuplicates);
}
return self::collectByDerivedKeyStrict($array, $keyOrCallback, $keepDuplicates);
}
/**
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
private static function collectByDerivedKeyLoose(
array $array,
string|callable $keyOrCallback,
bool $keepDuplicates,
): array {
$results = [];
$seen = [];
foreach ($array as $index => $row) {
if (is_string($keyOrCallback)) {
if (!is_array($row) || !array_key_exists($keyOrCallback, $row)) {
continue;
}
$derived = $row[$keyOrCallback];
} else {
$derived = self::invokeRowCallback($keyOrCallback, $row, $index);
}
$alreadySeen = in_array($derived, $seen, false);
if ($alreadySeen === $keepDuplicates) {
$results[$index] = $row;
}
if (!$alreadySeen) {
$seen[] = $derived;
}
}
return $results;
}
/**
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
private static function collectByDerivedKeyStrict(
array $array,
string|callable $keyOrCallback,
bool $keepDuplicates,
): array {
$results = [];
$seen = [];
$digestBuckets = [];
$fallback = [];
foreach ($array as $index => $row) {
if (is_string($keyOrCallback)) {
if (!is_array($row) || !array_key_exists($keyOrCallback, $row)) {
continue;
}
$derived = $row[$keyOrCallback];
} else {
$derived = self::invokeRowCallback($keyOrCallback, $row, $index);
}
$alreadySeen = ArrayValueSetOps::strictValueAlreadySeen(
$derived,
$seen,
$digestBuckets,
$fallback,
);
if ($alreadySeen === $keepDuplicates) {
$results[$index] = $row;
}
}
return $results;
}
/**
* @param array<int, array{values:array<array-key, mixed>, desc:bool, options:int}> $criteria
*/
private static function compareByManyCriteria(int|string $leftKey, int|string $rightKey, array $criteria): int
{
foreach ($criteria as $criterion) {
$leftValue = $criterion['values'][$leftKey];
$rightValue = $criterion['values'][$rightKey];
$comparison = self::compareSortValues($leftValue, $rightValue, $criterion['options']);
if ($comparison !== 0) {
return self::applySortDirection($comparison, $criterion['desc']);
}
}
return 0;
}
/**
* Compare two values according to PHP sort options.
*/
private static function compareSortValues(mixed $left, mixed $right, int $options): int
{
if ($left === $right) {
return 0;
}
$caseInsensitive = (bool) ($options & \SORT_FLAG_CASE);
$baseOption = $options & ~\SORT_FLAG_CASE;
return match ($baseOption) {
\SORT_NUMERIC => self::asNumeric($left) <=> self::asNumeric($right),
\SORT_STRING => $caseInsensitive
? strcasecmp(self::asString($left), self::asString($right))
: strcmp(self::asString($left), self::asString($right)),
\SORT_NATURAL => $caseInsensitive
? strnatcasecmp(self::asString($left), self::asString($right))
: strnatcmp(self::asString($left), self::asString($right)),
\SORT_LOCALE_STRING => strcoll(self::asString($left), self::asString($right)),
default => $left <=> $right,
};
}
private static function extractComparableValue(mixed $row, string|callable $keyOrCallback, int|string $key): float|int|null
{
if (!is_string($keyOrCallback)) {
$result = self::invokeRowCallback($keyOrCallback, $row, $key);
return ArraySingleOps::numericValue($result);
}
if (is_array($row) && array_key_exists($keyOrCallback, $row)) {
return ArraySingleOps::numericValue($row[$keyOrCallback]);
}
return null;
}
private static function extractRowTextValue(mixed $row, string $key): ?string
{
if (!is_array($row) || !array_key_exists($key, $row)) {
return null;
}
$value = $row[$key];
if (!is_scalar($value) && $value !== null) {
return null;
}
return (string) $value;
}
private static function extractSummableValue(mixed $row, string|callable|null $keyOrCallback, int|string $key): float|int
{
if ($keyOrCallback === null) {
return ArraySingleOps::numericValue($row) ?? 0;
}
if (!is_string($keyOrCallback)) {
$result = self::invokeRowCallback($keyOrCallback, $row, $key);
return ArraySingleOps::numericValue($result) ?? 0;
}
if (is_array($row) && isset($row[$keyOrCallback])) {
return ArraySingleOps::numericValue($row[$keyOrCallback]) ?? 0;
}
return 0;
}
/**
* @param array<array-key, mixed> $array
* @return array<array-key, mixed>
*/
private static function filterByNullState(array $array, string $key, bool $expectNull): array
{
$results = [];
foreach ($array as $index => $row) {
if (!is_array($row) || !array_key_exists($key, $row)) {
continue;
}
$isNull = $row[$key] === null;
if (($expectNull && $isNull) || (!$expectNull && !$isNull)) {
$results[$index] = $row;
}
}
return $results;
}
/**