Repository navigation
Expand file tree
/
Copy pathArrayHelper.php
More file actions
901 lines (729 loc) · 25 KB
/
Copy pathArrayHelper.php
File metadata and controls
901 lines (729 loc) · 25 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
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Helpers\Array;
use ArrayAccess;
use CodeIgniter\Entity\Entity;
use CodeIgniter\Exceptions\InvalidArgumentException;
use stdClass;
use Traversable;
/**
* @internal This is internal implementation for the framework.
*
* If there are any methods that should be provided, make them
* public APIs via helper functions.
*/
final class ArrayHelper
{
/**
* Searches an array through dot syntax. Supports wildcard searches,
* like `foo.*.bar`.
*
* @used-by dot_array_search()
*
* @param string $index The index as dot array syntax.
* @param array<array-key, mixed>|object $array
*
* @return mixed
*/
public static function dotSearch(string $index, array|object $array)
{
return self::arraySearchDot(self::convertToArray($index), $array);
}
/**
* @param string $index The index as dot array syntax.
*
* @return list<string> The index as an array.
*/
private static function convertToArray(string $index): array
{
$trimmed = rtrim($index, '* ');
if ($trimmed === '') {
return [];
}
// Fast path: no escaped dots, skip the regex entirely.
if (! str_contains($trimmed, '\\.')) {
return array_values(array_filter(
explode('.', $trimmed),
static fn ($s): bool => $s !== '',
));
}
// See https://regex101.com/r/44Ipql/1
$segments = preg_split('/(?<!\\\\)\./', $trimmed, 0, PREG_SPLIT_NO_EMPTY);
return array_map(
static fn ($key): string => str_replace('\.', '.', $key),
$segments,
);
}
/**
* Recursively search the array with wildcards.
*
* @used-by dotSearch()
*
* @param list<string> $indexes
* @param array<array-key, mixed>|object $array
*
* @return mixed
*/
private static function arraySearchDot(array $indexes, array|object $array)
{
// If index is empty, returns null.
if ($indexes === []) {
return null;
}
// Grab the current index
$currentIndex = array_shift($indexes);
// Handle Wildcard (*)
if ($currentIndex === '*') {
$answer = [];
foreach (self::entries($array) as $value) {
if (! self::isNavigable($value)) {
return null;
}
$answer[] = self::arraySearchDot($indexes, $value);
}
$answer = array_filter($answer, static fn ($value): bool => $value !== null);
if ($answer !== []) {
// If array only has one element, we return that element for BC.
return count($answer) === 1 ? current($answer) : $answer;
}
return null;
}
[$found, $value] = self::resolve($array, $currentIndex);
if (! $found) {
return null;
}
// If this is the last index, make sure to return it now,
// and not try to recurse through things.
if ($indexes === []) {
return $value;
}
// Do we need to recursively search this value?
if ((is_array($value) && $value !== []) || is_object($value)) {
return self::arraySearchDot($indexes, $value);
}
// Otherwise, not found.
return null;
}
/**
* array_key_exists() with dot array syntax.
*
* If wildcard `*` is used, all items for the key after it must have the key.
*
* @param array<array-key, mixed>|object $array
*/
public static function dotHas(string $index, array|object $array): bool
{
self::ensureValidWildcardPattern($index);
$indexes = self::convertToArray($index);
if ($indexes === []) {
return false;
}
return self::hasByDotPath($array, $indexes);
}
/**
* Recursively check key existence by dot path, including wildcard support.
*
* @param array<array-key, mixed>|object $array
* @param list<string> $indexes
*/
private static function hasByDotPath(array|object $array, array $indexes): bool
{
if ($indexes === []) {
return true;
}
$currentIndex = array_shift($indexes);
if ($currentIndex === '*') {
$entries = self::entries($array);
if ($entries === []) {
return false;
}
foreach ($entries as $item) {
if (! self::isNavigable($item) || ! self::hasByDotPath($item, $indexes)) {
return false;
}
}
return true;
}
[$found, $value] = self::resolve($array, $currentIndex);
if (! $found) {
return false;
}
if ($indexes === []) {
return true;
}
if (! self::isNavigable($value)) {
return false;
}
return self::hasByDotPath($value, $indexes);
}
/**
* Sets a value by dot array syntax.
*
* @param array<array-key, mixed> $array
*/
public static function dotSet(array &$array, string $index, mixed $value): void
{
self::ensureValidWildcardPattern($index);
$indexes = self::convertToArray($index);
if ($indexes === []) {
return;
}
self::setByDotPath($array, $indexes, $value);
}
/**
* Removes a value by dot array syntax.
*
* @param array<array-key, mixed> $array
*/
public static function dotUnset(array &$array, string $index): bool
{
self::ensureValidWildcardPattern($index, true);
if ($index === '*') {
return self::clearByDotPath($array, []) > 0;
}
$indexes = self::convertToArray($index);
if ($indexes === []) {
return false;
}
if (str_ends_with($index, '*')) {
return self::clearByDotPath($array, $indexes) > 0;
}
return self::unsetByDotPath($array, $indexes) > 0;
}
/**
* Gets only the specified keys using dot syntax.
*
* @param array<array-key, mixed>|object $array
* @param list<string>|string $indexes
*
* @return array<array-key, mixed>
*/
public static function dotOnly(array|object $array, array|string $indexes): array
{
$indexes = is_string($indexes) ? [$indexes] : $indexes;
$result = [];
foreach ($indexes as $index) {
self::ensureValidWildcardPattern($index, true);
if ($index === '*') {
$result = [...$result, ...(is_object($array) ? self::toIterable($array) : $array)];
continue;
}
$segments = self::convertToArray($index);
if ($segments === []) {
continue;
}
self::projectByDotPath($array, $segments, $result);
}
return $result;
}
/**
* Gets all keys except the specified ones using dot syntax.
*
* @param array<array-key, mixed>|object $array
* @param list<string>|string $indexes
*
* @return array<array-key, mixed>
*/
public static function dotExcept(array|object $array, array|string $indexes): array
{
$indexes = is_string($indexes) ? [$indexes] : $indexes;
// Open only the root into an array view; nested values (including
// objects) are preserved until a path actually descends into them.
$result = self::entries($array);
foreach ($indexes as $index) {
self::ensureValidWildcardPattern($index, true);
if ($index === '*') {
$result = [];
continue;
}
$segments = self::convertToArray($index);
if ($segments === []) {
continue;
}
if (str_ends_with($index, '*')) {
self::excludeChildrenByDotPath($result, $segments);
continue;
}
self::excludeByDotPath($result, $segments);
}
return $result;
}
/**
* Groups all rows by their index values. Result's depth equals number of indexes
*
* @used-by array_group_by()
*
* @param array<array-key, mixed> $array Data array (i.e. from query result)
* @param list<string> $indexes Indexes to group by. Dot syntax used. Returns $array if empty
* @param bool $includeEmpty If true, null and '' are also added as valid keys to group
*
* @return array<array-key, mixed> Result array where rows are grouped together by indexes values.
*/
public static function groupBy(array $array, array $indexes, bool $includeEmpty = false): array
{
if ($indexes === []) {
return $array;
}
$result = [];
foreach ($array as $row) {
$result = self::arrayAttachIndexedValue($result, $row, $indexes, $includeEmpty);
}
return $result;
}
/**
* Recursively attach $row to the $indexes path of values found by
* dot syntax.
*
* @used-by groupBy()
*
* @param array<array-key, mixed> $result
* @param array<array-key, mixed>|object $row
* @param list<string> $indexes
*
* @return array<array-key, mixed>
*/
private static function arrayAttachIndexedValue(
array $result,
array|object $row,
array $indexes,
bool $includeEmpty,
): array {
if (($index = array_shift($indexes)) === null) {
$result[] = $row;
return $result;
}
$value = self::dotSearch($index, $row);
if (! is_scalar($value)) {
$value = '';
}
if (is_bool($value)) {
$value = (int) $value;
}
if (! $includeEmpty && $value === '') {
return $result;
}
if (! array_key_exists($value, $result)) {
$result[$value] = [];
}
$result[$value] = self::arrayAttachIndexedValue($result[$value], $row, $indexes, $includeEmpty);
return $result;
}
/**
* Compare recursively two associative arrays and return difference as new array.
* Returns keys that exist in `$original` but not in `$compareWith`.
*
* @param array<array-key, mixed> $original
* @param array<array-key, mixed> $compareWith
*
* @return array<array-key, mixed>
*/
public static function recursiveDiff(array $original, array $compareWith): array
{
$difference = [];
if ($original === []) {
return [];
}
if ($compareWith === []) {
return $original;
}
foreach ($original as $originalKey => $originalValue) {
if ($originalValue === []) {
continue;
}
if (is_array($originalValue)) {
$diffArrays = [];
if (isset($compareWith[$originalKey]) && is_array($compareWith[$originalKey])) {
$diffArrays = self::recursiveDiff($originalValue, $compareWith[$originalKey]);
} else {
$difference[$originalKey] = $originalValue;
}
if ($diffArrays !== []) {
$difference[$originalKey] = $diffArrays;
}
} elseif (is_string($originalValue) && ! array_key_exists($originalKey, $compareWith)) {
$difference[$originalKey] = $originalValue;
}
}
return $difference;
}
/**
* Recursively count all keys.
*
* @param array<array-key, mixed> $array
*/
public static function recursiveCount(array $array, int $counter = 0): int
{
foreach ($array as $value) {
if (is_array($value)) {
$counter = self::recursiveCount($value, $counter);
}
$counter++;
}
return $counter;
}
/**
* Sorts array values in natural order
* If the value is an array, you need to specify the $sortByIndex of the key to sort
*
* @param list<int|list<int|string>|string> $array
* @param int|string|null $sortByIndex
*/
public static function sortValuesByNatural(array &$array, $sortByIndex = null): true
{
return usort($array, static function ($currentValue, $nextValue) use ($sortByIndex): int {
if ($sortByIndex !== null) {
return strnatcmp((string) $currentValue[$sortByIndex], (string) $nextValue[$sortByIndex]);
}
return strnatcmp((string) $currentValue, (string) $nextValue);
});
}
/**
* Resolve a key against an array or object node, walking the access chain
* (Entity, ArrayAccess, public properties, magic `__isset`/`__get`) once.
*
* @param array<array-key, mixed>|object $node
*
* @return array{bool, mixed} The pair [found, value].
*/
private static function resolve(array|object $node, string $key): array
{
if (is_array($node)) {
return array_key_exists($key, $node) ? [true, $node[$key]] : [false, null];
}
$array = self::entityToArray($node);
if ($array !== null) {
return array_key_exists($key, $array) ? [true, $array[$key]] : [false, null];
}
if ($node instanceof ArrayAccess && $node->offsetExists($key)) {
return [true, $node->offsetGet($key)];
}
$properties = get_object_vars($node);
if (array_key_exists($key, $properties)) {
return [true, $properties[$key]];
}
return isset($node->{$key}) ? [true, $node->{$key}] : [false, null];
}
/**
* Whether keys can be resolved from this value, i.e. it is an array or an
* object that exposes a key surface: an expandable container, an
* `ArrayAccess`, or one relying on magic `__get`. Pure value-objects
* (e.g. `DateTimeImmutable`) are not navigable.
*
* Direct key lookup can support more object types than wildcard traversal:
* `ArrayAccess` and magic-only objects can resolve `user.id`, but cannot be
* enumerated for `user.*` unless they are also expandable.
*/
private static function isNavigable(mixed $value): bool
{
if (is_array($value)) {
return true;
}
return is_object($value)
&& (self::isExpandable($value)
|| $value instanceof ArrayAccess
|| method_exists($value, '__get'));
}
/**
* Entries of an array or object node for wildcard traversal.
*
* @param array<array-key, mixed>|object $node
*
* @return array<array-key, mixed>
*/
private static function entries(array|object $node): array
{
return is_object($node) ? self::toIterable($node) : $node;
}
/**
* @return array<array-key, mixed>|null
*/
private static function entityToArray(object $data): ?array
{
if ($data instanceof Entity) {
return $data->toArray();
}
return null;
}
/**
* Normalize an object to an array safe to iterate with foreach.
*
* Entities are converted via toArray() so internal properties like
* `_options` or `_cast` are not exposed. Other Traversable objects are
* converted to an array with their keys preserved; plain objects fall back
* to their public properties.
*
* @return array<array-key, mixed>
*/
private static function toIterable(object $data): array
{
$array = self::entityToArray($data);
if ($array !== null) {
return $array;
}
if ($data instanceof Traversable) {
return iterator_to_array($data);
}
return get_object_vars($data);
}
/**
* Whether an object should be expanded into an array when building output.
*
* Only enumerable containers are expanded: entities, `stdClass`, other
* `Traversable` objects, and plain objects exposing public properties.
* Opaque objects with no enumerable key surface (value-objects such as
* `DateTimeImmutable`, magic-only or pure `ArrayAccess` objects) are
* preserved as-is, since they cannot be faithfully rebuilt as an array.
*/
private static function isExpandable(object $value): bool
{
return $value instanceof Entity
|| $value instanceof stdClass
|| $value instanceof Traversable
|| get_object_vars($value) !== [];
}
/**
* Ensure a value can be descended into for a partial exclusion/projection.
*
* Arrays pass through; expandable objects are converted to an array view
* in place (this is the only point where output structure is fabricated).
* Anything else (scalars, value-objects, magic-only or pure `ArrayAccess`
* objects) is left untouched and reported as non-descendable.
*/
private static function expandForDescent(mixed &$value): bool
{
if (is_array($value)) {
return true;
}
if (is_object($value) && self::isExpandable($value)) {
$value = self::entries($value);
return true;
}
return false;
}
/**
* Throws exception for invalid wildcard patterns.
*/
private static function ensureValidWildcardPattern(string $index, bool $allowTrailingWildcard = false): void
{
if ((! $allowTrailingWildcard && str_ends_with($index, '*')) || str_contains($index, '*.*')) {
throw new InvalidArgumentException(
'You must set key right after "*". Invalid index: "' . $index . '"',
);
}
}
/**
* Set value recursively by dot path, including wildcard support.
*
* @param array<array-key, mixed> $array
* @param list<string> $indexes
*/
private static function setByDotPath(array &$array, array $indexes, mixed $value): void
{
if ($indexes === []) {
return;
}
$currentIndex = array_shift($indexes);
if ($currentIndex === '*') {
foreach ($array as &$item) {
if (! is_array($item)) {
continue;
}
self::setByDotPath($item, $indexes, $value);
}
unset($item);
return;
}
if ($indexes === []) {
$array[$currentIndex] = $value;
return;
}
if (! isset($array[$currentIndex]) || ! is_array($array[$currentIndex])) {
$array[$currentIndex] = [];
}
self::setByDotPath($array[$currentIndex], $indexes, $value);
}
/**
* Unset value recursively by dot path, including wildcard support.
*
* @param array<array-key, mixed> $array
* @param list<string> $indexes
*/
private static function unsetByDotPath(array &$array, array $indexes): int
{
if ($indexes === []) {
return 0;
}
$currentIndex = array_shift($indexes);
if ($currentIndex === '*') {
$removed = 0;
foreach ($array as &$item) {
if (! is_array($item)) {
continue;
}
$removed += self::unsetByDotPath($item, $indexes);
}
unset($item);
return $removed;
}
if ($indexes === []) {
if (! array_key_exists($currentIndex, $array)) {
return 0;
}
unset($array[$currentIndex]);
return 1;
}
if (! isset($array[$currentIndex]) || ! is_array($array[$currentIndex])) {
return 0;
}
return self::unsetByDotPath($array[$currentIndex], $indexes);
}
/**
* Clears all children under the specified path.
*
* @param array<array-key, mixed> $array
* @param list<string> $indexes
*/
private static function clearByDotPath(array &$array, array $indexes): int
{
if ($indexes === []) {
$count = count($array);
$array = [];
return $count;
}
$currentIndex = array_shift($indexes);
if ($currentIndex === '*') {
$cleared = 0;
foreach ($array as &$item) {
if (! is_array($item)) {
continue;
}
$cleared += self::clearByDotPath($item, $indexes);
}
unset($item);
return $cleared;
}
if (! array_key_exists($currentIndex, $array) || ! is_array($array[$currentIndex])) {
return 0;
}
return self::clearByDotPath($array[$currentIndex], $indexes);
}
/**
* Removes a value by dot path for dotExcept(). Objects are expanded to an
* array view only when the path descends into them, so untouched branches
* keep their original values (including objects).
*
* @param array<array-key, mixed> $array
* @param list<string> $indexes
*/
private static function excludeByDotPath(array &$array, array $indexes): int
{
if ($indexes === []) {
return 0;
}
$currentIndex = array_shift($indexes);
if ($currentIndex === '*') {
$removed = 0;
foreach ($array as &$item) {
if (self::expandForDescent($item)) {
$removed += self::excludeByDotPath($item, $indexes);
}
}
unset($item);
return $removed;
}
if ($indexes === []) {
if (! array_key_exists($currentIndex, $array)) {
return 0;
}
unset($array[$currentIndex]);
return 1;
}
if (! array_key_exists($currentIndex, $array) || ! self::expandForDescent($array[$currentIndex])) {
return 0;
}
return self::excludeByDotPath($array[$currentIndex], $indexes);
}
/**
* Clears all children under the specified path for dotExcept(), expanding
* objects to an array view only along the descended path.
*
* @param array<array-key, mixed> $array
* @param list<string> $indexes
*/
private static function excludeChildrenByDotPath(array &$array, array $indexes): int
{
if ($indexes === []) {
$count = count($array);
$array = [];
return $count;
}
$currentIndex = array_shift($indexes);
if ($currentIndex === '*') {
$cleared = 0;
foreach ($array as &$item) {
if (self::expandForDescent($item)) {
$cleared += self::excludeChildrenByDotPath($item, $indexes);
}
}
unset($item);
return $cleared;
}
if (! array_key_exists($currentIndex, $array) || ! self::expandForDescent($array[$currentIndex])) {
return 0;
}
return self::excludeChildrenByDotPath($array[$currentIndex], $indexes);
}
/**
* Projects matching paths from source into result with preserved structure.
*
* @param array<array-key, mixed>|object $source
* @param list<string> $indexes
* @param list<string> $prefix
* @param array<array-key, mixed> $result
*/
private static function projectByDotPath(
array|object $source,
array $indexes,
array &$result,
array $prefix = [],
): void {
if ($indexes === []) {
// The whole node was selected: preserve it as-is. Output structure
// is only fabricated for the projection skeleton above this leaf.
self::setByDotPath($result, $prefix, $source);
return;
}
$currentIndex = array_shift($indexes);
if ($currentIndex === '*') {
foreach (self::entries($source) as $key => $value) {
if (! self::isNavigable($value)) {
if ($indexes === []) {
self::setByDotPath($result, [...$prefix, (string) $key], $value);
}
continue;
}
self::projectByDotPath($value, $indexes, $result, [...$prefix, (string) $key]);
}
return;
}
[$found, $value] = self::resolve($source, $currentIndex);
if (! $found) {
return;
}
if (! self::isNavigable($value)) {
if ($indexes === []) {
self::setByDotPath($result, [...$prefix, $currentIndex], $value);
}
return;
}
self::projectByDotPath($value, $indexes, $result, [...$prefix, $currentIndex]);
}
}