-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathArr.php
More file actions
executable file
·794 lines (697 loc) · 21.5 KB
/
Arr.php
File metadata and controls
executable file
·794 lines (697 loc) · 21.5 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
<?php
declare(strict_types=1);
namespace HiFolks\DataType;
use ArrayAccess;
use Closure;
use Countable;
use HiFolks\DataType\Traits\Calculable;
use Iterator;
use Traversable;
/**
* Class Arr
* @package HiFolks\DataType
*
* @implements Iterator<int|string, mixed>
* @implements ArrayAccess<int|string, mixed>
*/
final class Arr implements Iterator, ArrayAccess, Countable
{
use Calculable;
/** @param array<int|string, mixed> $arr */
public function __construct(private array $arr = [])
{
}
public static function fromFunction(callable $callable, int $count): Arr
{
$array = [];
for ($i = 0; $i < $count; $i++) {
$array[$i] = $callable($i);
}
return self::make($array);
}
public static function fromValue(mixed $value, int $count): self
{
return self::make(array_fill(0, $count, $value));
}
/**
* Creates a new Arr instance from a string or array-like object.
*
* @param iterable<int|string, mixed>|string $arrayLike
*/
public static function from(iterable|string $arrayLike, ?Closure $mapFn = null): self
{
if (is_string($arrayLike)) {
$arrayLike = str_split($arrayLike);
}
if ($arrayLike instanceof Traversable) {
$arrayLike = iterator_to_array($arrayLike);
}
$array = self::make($arrayLike);
if (! is_callable($mapFn)) {
return $array;
}
return $array->map($mapFn);
}
/** @param array<int|string, mixed> $arr */
public static function make(array $arr = []): self
{
return new self($arr);
}
/**
* Creates a new Arr instance from a variable number of arguments,
* regardless of number or type of the arguments.
*
* @return Arr object
*/
public static function of(mixed ...$elements): self
{
return self::make($elements);
}
public function count(): int
{
return count($this->arr);
}
public function length(): int
{
return $this->count();
}
/**
* Get the array
* @return array<int|string, mixed>
*/
public function arr(): array
{
return $this->arr;
}
/**
* Get the element with $key
*
* @param non-empty-string $charNestedKey
*/
public function get(int|string $key, mixed $defaultValue = null, string $charNestedKey = "."): mixed
{
if (is_string($key)) {
$keyString = strval($key);
if (str_contains($keyString, $charNestedKey)) {
$nestedValue = $this->arr;
foreach (explode($charNestedKey, $keyString) as $nestedKey) {
if (is_array($nestedValue) && array_key_exists($nestedKey, $nestedValue)) {
$nestedValue = $nestedValue[$nestedKey];
} else {
return $defaultValue;
}
}
return $nestedValue;
}
}
return $this->arr[$key] ?? $defaultValue;
}
/**
* Get the element with $key as Arr object
* This is helpful when the element is an array, and you
* need to get the Arr object instead of the classic array
* In the case the $key doesn't exist, an empty Arr can be returned
* @param non-empty-string $charNestedKey
*/
public function getArr(int|string $key, mixed $defaultValue = null, string $charNestedKey = "."): Arr
{
$value = $this->getArrNullable($key, $defaultValue, $charNestedKey);
if (is_null($value)) {
return Arr::make([]);
}
return $value;
}
/**
* Get the element with $key as Arr object
* This is helpful when the element is an array, and you
* need to get the Arr object instead of the classic array
* In the case the $key doesn't exist, null can be returned
* @param non-empty-string $charNestedKey
*/
public function getArrNullable(int|string $key, mixed $defaultValue = null, string $charNestedKey = "."): Arr|null
{
$value = $this->get($key, $defaultValue, $charNestedKey);
if (is_null($value)) {
return null;
}
if (is_scalar($value)) {
return self::make([ $value]);
}
if (is_array($value)) {
return self::make($value);
}
if ($value instanceof Arr) {
return $value;
}
return Arr::make([]);
}
/**
* Set a value to a specific $key
* You can use the dot notation for setting a nested value.
* @param non-empty-string $charNestedKey
*/
public function set(int|string $key, mixed $value, string $charNestedKey = "."): void
{
if (is_string($key)) {
$array = &$this->arr;
$keys = explode($charNestedKey, $key);
foreach ($keys as $i => $key) {
if (count($keys) === 1) {
break;
}
unset($keys[$i]);
if (!isset($array[$key]) || !is_array($array[$key])) {
$array[$key] = [];
}
$array = &$array[$key];
}
$lastKey = array_shift($keys);
if ($lastKey !== null) {
$array[$lastKey] = $value;
}
return;
}
$this->arr[$key] = $value;
}
/**
* Unset an array element by their key if it exists
*/
public function unset(int|string $key): bool
{
if ($this->get($key)) {
unset($this->arr[$key]);
return true;
}
return false;
}
/**
* Takes an integer value $index and returns the item at that index,
* allowing for positive and negative integers.
* Negative integers count back from the last item in the array.
* For lists, map, associative array, uses get() method.
*
* @param int $index the index of the element of the array (negative cont back from last item
* @return mixed item value (null if $index is not existent
*/
public function at(int $index): mixed
{
if ($index < 0) {
$index = $this->length() + $index;
}
return $this->get($index);
}
/**
* Return the current element
*
* @link https://php.net/manual/en/iterator.current.php
*
* @return mixed Can return any type.
*/
public function current(): mixed
{
return current($this->arr);
}
/**
* Move forward to next element
*
* @link https://php.net/manual/en/iterator.next.php
*
* @return void Any returned value is ignored.
*/
public function next(): void
{
next($this->arr);
}
public function prev(): mixed
{
return prev($this->arr);
}
/**
* Return the key of the current element
*
* @link https://php.net/manual/en/iterator.key.php
*
* @return string|int|null scalar on success, or null on failure.
*/
public function key(): string|int|null
{
return key($this->arr);
}
/**
* Checks if current position is valid
*
* @link https://php.net/manual/en/iterator.valid.php
*
* @return bool The return value will be casted to boolean and then evaluated.
* Returns true on success or false on failure.
*/
public function valid(): bool
{
return ! is_null($this->key());
}
/**
* Rewind the Iterator to the first element
*
* @link https://php.net/manual/en/iterator.rewind.php
*
* @return void Any returned value is ignored.
*/
public function rewind(): void
{
reset($this->arr);
}
/**
* It executes a provided function ($callback) once for each element.
*/
public function forEach(callable $callback): self
{
$x = array_map($callback, $this->arr, array_keys($this->arr));
return self::make($x);
}
/**
* Returns a new array [] or a new Arr object that contains the keys
* for each index in the Arr object
* It returns Arr or [] depending on $returnArrClass value
*
* @param bool $returnArrClass true if you need Arr object
* @return array<int|string, mixed>|Arr
*/
public function keys(bool $returnArrClass = false): array|Arr
{
if ($returnArrClass) {
return self::make(array_keys($this->arr));
}
return array_keys($this->arr);
}
/**
* Add an $element to the end of an array and returns new length of the array.
*/
public function push(mixed ...$element): int
{
return array_push($this->arr, ...$element);
}
/**
* It removes the last element from an array and returns that element.
* This method changes the length of the Arr
*
* @return mixed the element removed
*/
public function pop(): mixed
{
return array_pop($this->arr);
}
/**
* Add element to start of Arr and return new length
*
* @return int the new length of the array upon which the method was called.
*/
public function unshift(mixed ...$element): int
{
return array_unshift($this->arr, ...$element);
}
/**
* Removes the first element from an array and
* returns that removed element.
* This method changes the length of the array.
*
* @return mixed the removed element
*/
public function shift(): mixed
{
return array_shift($this->arr);
}
/**
* Append arrays into the current one
* @param array<int|string, mixed> $elements
*/
public function append(...$elements): self
{
$this->arr = array_merge($this->arr, ...$elements);
return $this;
}
/**
* Returns new Arr joining more elements: array, Arr, scalar type.
* This method does not change the existing Arr object,
* but instead returns a new Arr object
*
*/
public function concat(mixed ...$elements): Arr
{
$array = $this->arr;
foreach ($elements as $element) {
switch (gettype($element)) {
case 'array':
/** @var array<int|string, mixed> $element */
$array = array_merge($array, $element);
break;
case 'string':
case 'integer':
case 'boolean':
case 'double':
$array = array_merge($array, [$element]);
break;
case 'object':
if ($element instanceof Arr) {
$array = array_merge($array, $element->arr());
}
break;
}
}
return self::make($array);
}
/**
* Joins all elements into a string, separated by $separator
*
* @param string $separator the separator, could be also a string with more than 1 char
*/
public function join(string $separator = ','): string
{
return implode($separator, $this->arr);
}
/**
* Returns as new Arr instance of a portion of an array into a new Arr object
* selected from $start to $end ($end not included)
* where start and end represent the index of items in that array.
* The original array will not be modified
*
* @param int $start start index (array start from 0, start included)
* @param int|null $end end index (array starts from 0, end not included)
*/
public function slice(int $start, ?int $end = null): Arr
{
if (is_null($end)) {
$end = $this->length();
}
if ($end < 0) {
$end = $this->length() + $end;
}
if ($start < 0) {
$start = $this->length() + $start;
}
return self::make(array_slice($this->arr, $start, $end - $start));
}
/**
* Returns index of first occurrence of element in arr
*
* @return string|int|bool the index of element found. If it is not found, false is returned
*/
public function indexOf(mixed $searchElement): string|int|bool
{
return array_search($searchElement, $this->arr, true);
}
/**
* Returns index of last occurrence of element in Arr
*
* @return string|int|bool the index of element found. If it is not found, false is returned
*/
public function lastIndexOf(mixed $searchElement): string|int|bool
{
return array_search($searchElement, array_reverse($this->arr, true), true);
}
/**
* Returns true if all elements in Arr pass the test in fn.
*/
public function every(callable $callback): bool
{
foreach ($this->arr as $key => $element) {
if (! $callback($element, $key)) {
return false;
}
}
return true;
}
/**
* Returns true if all elements in arr pass the test in fn.
* Tests whether at least one element in the array passes the test
* implemented by the provided function.
* It returns true if, in the array, it finds an element for which
* the provided function returns true;
* otherwise it returns false.
* It doesn't modify the array.
*/
public function some(callable $callback): bool
{
foreach ($this->arr as $key => $element) {
if ($callback($element, $key)) {
return true;
}
}
return false;
}
/**
* Determines whether the array includes a certain value $element among its entries,
* returning true or false as appropriate
*/
public function includes(mixed $element, ?int $fromIndex = null): bool
{
if (is_null($fromIndex)) {
return in_array($element, $this->arr, true);
}
return in_array($element, array_slice($this->arr, $fromIndex), true);
}
/**
* Returns new Arr with elements of arr passing the filtering function fn
*
* @param callable $callback the function for filtering
*/
public function filter(callable $callback): Arr
{
return self::make(array_filter($this->arr, $callback));
}
/**
* Returns index of the first element in arr passing the callback function
*
* @param callable $callback the function for finding the index
*/
public function findIndex(callable $callback): int|string
{
foreach ($this->arr as $key => $element) {
if ($callback($element, $key, $this->arr)) {
return $key;
}
}
return -1;
}
/**
* Returns a new Arr populated with the results of
* calling a provided function on every element in the calling array
*/
public function map(callable $callback): Arr
{
return $this->forEach($callback);
}
/**
* Returns a new Arr object as flatten array with subarrays concatenated
*/
public function flat(): self
{
$array = array_reduce(
$this->arr,
fn ($result, $element): array => array_merge($result, is_array($element) ? [...$element] : [$element]),
[]
);
return self::make($array);
}
/**
* The flatMap method is identical to a map followed by a call to flat of depth 1
*/
public function flatMap(callable $callback): self
{
$array = Arr::make([]);
foreach ($this->arr as $key => $element) {
if (is_array($element)) {
$array->push(...self::make($element)
->forEach($callback)
->arr());
continue;
}
$a = $callback($element, $key);
if (is_array($a)) {
$array->push(...$a);
} else {
$array->push($a);
}
}
return $array;
}
/**
* Changes all elements in range from $start for $count, to the specified value
*
* @param int $start start index (from 0)
* @param int|null $end end index (default, the end of array)
*/
public function fill(mixed $value, int $start = 0, ?int $end = null): void
{
if (is_null($end)) {
$end = $this->length() - 1;
}
for ($i = $start; $i <= $end; $i++) {
$this->arr[$i] = $value;
}
}
/**
* Executes a user-supplied $callback callback function on each element of the array,
* in order, passing in the return value from the calculation on the preceding element.
* The final result of running the reducer across all elements of the array
* is a single value.
*
* @return mixed the result
*/
public function reduce(callable $callback, mixed $initialValue = 0): mixed
{
return array_reduce($this->arr, $callback, $initialValue);
}
/**
* Applies a function against an accumulator and each value of the array
* (from right-to-left) to reduce it to a single value.
*/
public function reduceRight(callable $callback, mixed $initialValue = 0): mixed
{
return array_reduce(array_reverse($this->arr), $callback, $initialValue);
}
/**
* Reverses an array in place, and it returns also a new instance of Arr
* The first array element becomes the last,
* and the last array element becomes the first.
*
* @param bool $preserve_keys if set to true keys are preserved
*/
public function reverse(bool $preserve_keys = false): Arr
{
$this->arr = array_reverse($this->arr, $preserve_keys);
return self::make($this->arr);
}
/**
* Sorts the elements of an Arr object in place and returns the sorted Arr object.
* The default sort order is ascending
*/
public function sort(): Arr
{
sort($this->arr);
return $this;
}
/**
* Changes content of arr removing, replacing and adding elements
* Changes the contents of an array by removing or replacing existing elements
* and/or adding new elements in place.
* To access part of an array without modifying it, see slice().
*
* @param int $start the index at which to start changing the array
* @param int|null $deleteCount an integer indicating the number of elements in the array to remove from $start
* @return Arr an array containing the deleted elements
*/
public function splice(int $start, ?int $deleteCount = null, mixed $newElements = []): Arr
{
return self::make(array_splice($this->arr, $start, $deleteCount, $newElements));
}
/**
* Returns a string representing arr its elements (same as arr.join(','))
*/
public function toString(): string
{
return $this->join();
}
/**
* Returns true if the input is an array
*
* @return bool true if $input is an array, false otherwise
*/
public static function isArray(mixed $input): bool
{
return is_array($input);
}
/**
* This method is executed when using isset() or empty()
*/
public function offsetExists(mixed $offset): bool
{
return array_key_exists($offset, $this->arr);
}
/**
* Offset to retrieve
*/
public function offsetGet(mixed $offset): mixed
{
return $this->get($offset);
}
/**
* Offset to set
*/
public function offsetSet(mixed $offset, mixed $value): void
{
if (is_null($offset)) {
$this->arr[] = $value;
} else {
$this->arr[$offset] = $value;
}
}
/**
* This method will not be called when type-casting to (unset)
*/
public function offsetUnset(mixed $offset): void
{
unset($this->arr[$offset]);
}
/**
* It creates a new Arr object with the values of the current one (keys are skipped)
*
* @return Arr an array containing only the values (not keys)
*/
public function values(): self
{
return new self(array_values($this->arr));
}
/**
* @return Arr object that contains the key/value pairs for each index in the array
*/
public function entries(): self
{
$pairs = [];
foreach ($this->arr as $k => $v) {
$pairs[] = [$k, $v];
}
return self::make($pairs);
}
/**
* @param Callable $callback the function to find the matching element
* @return mixed the first element in the array that satisfies
* the provided function
*/
public function find(callable $callback): mixed
{
foreach ($this->arr as $key => $element) {
if ($callback($element, $key, $this->arr)) {
return $element;
}
}
return null;
}
/**
* The copyWithin() method shallow copies part of an array to another
* location in the same array and returns it without modifying its length.
*
* @return array<int|string, mixed>
*/
public function copyWithin(int $target, int $start = 0, ?int $end = null): array
{
$arrayLength = $this->length();
$chuck = $this->slice($start, $end);
if ($target < 0) {
$target = $arrayLength - abs($target);
}
foreach ($chuck as $value) {
$this->arr[$target] = $value;
$target++;
}
$this->arr = $this->slice(0, $arrayLength)->arr;
return $this->arr;
}
/**
* Returns true if the input array is empty
* @return bool true if $input is an empty array, false otherwise
*/
public function isEmpty(): bool
{
return $this->length() === 0;
}
}