-
-
Notifications
You must be signed in to change notification settings - Fork 188
/
ArrayHelper.php
633 lines (599 loc) · 18.9 KB
/
ArrayHelper.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
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
<?php
namespace Neos\Eel\Helper;
/*
* This file is part of the Neos.Eel package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
use Neos\Eel\ProtectedContextAwareInterface;
/**
* Array helpers for Eel contexts
*
* The implementation uses the JavaScript specificiation where applicable, including EcmaScript 6 proposals.
*
* See https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array for a documentation and
* specification of the JavaScript implementation.
*
* @Flow\Proxy(false)
*/
class ArrayHelper implements ProtectedContextAwareInterface
{
/**
* Concatenate arrays or values to a new array
*
* @param iterable|mixed $array1 First array or value
* @param iterable|mixed $array2 Second array or value
* @param iterable|mixed $array_ Optional variable list of additional arrays / values
* @return array The array with concatenated arrays or values
*/
public function concat($array1, $array2, $array_ = null): array
{
$arguments = func_get_args();
foreach ($arguments as &$argument) {
if ($argument instanceof \Traversable) {
$argument = iterator_to_array($argument);
} elseif (!is_array($argument)) {
$argument = [$argument];
}
}
return array_merge(...$arguments);
}
/**
* Join values of an array with a separator
*
* @param iterable $array Array with values to join
* @param string $separator A separator for the values
* @return string A string with the joined values separated by the separator
*/
public function join(iterable $array, $separator = ','): string
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
return implode($separator, $array);
}
/**
* Extract a portion of an indexed array
*
* @param iterable $array The array (with numeric indices)
* @param int $begin
* @param int $end
* @return array
*/
public function slice(iterable $array, $begin, $end = null): array
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
if ($end === null) {
$end = count($array);
} elseif ($end < 0) {
$end = count($array) + $end;
}
$length = $end - $begin;
return array_slice($array, $begin, $length);
}
/**
* Returns an array in reverse order
*
* @param iterable $array The array
* @return array
*/
public function reverse(iterable $array): array
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
return array_reverse($array);
}
/**
* Get the array keys
*
* @param iterable $array The array
* @return array
*/
public function keys(iterable $array): array
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
return array_keys($array);
}
/**
* Get the array values
*
* @param iterable $array The array
* @return array
*/
public function values(iterable $array): array
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
return array_values($array);
}
/**
* Get the length of an array
*
* @param iterable $array The array
* @return int
*/
public function length(iterable $array): int
{
if ($array instanceof \Traversable) {
return iterator_count($array);
}
return count($array);
}
/**
* Check if an array is empty
*
* @param iterable $array The array
* @return bool true if the array is empty
*/
public function isEmpty(iterable $array): bool
{
return $this->length($array) === 0;
}
/**
* Get the first element of an array
*
* @param iterable $array The array
* @return mixed
*/
public function first(iterable $array)
{
if ($array instanceof \Traversable) {
foreach ($array as $value) {
return $value;
}
return false;
}
return reset($array);
}
/**
* Get the last element of an array
*
* @param iterable $array The array
* @return mixed
*/
public function last(iterable $array)
{
if ($array instanceof \Traversable) {
$result = false;
foreach ($array as $value) {
$result = $value;
}
return $result;
}
return end($array);
}
/**
* Returns the first index at which a given element can be found in the array,
* or -1 if it is not present
*
* @param iterable $array The array
* @param mixed $searchElement The element value to find
* @param int $fromIndex Position in the array to start the search.
* @return int
*/
public function indexOf(iterable $array, $searchElement, $fromIndex = null): int
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
if ($fromIndex !== null) {
$array = array_slice($array, $fromIndex, null, true);
}
$result = array_search($searchElement, $array, true);
if (is_string($result)) {
return array_search($result, array_keys($array), true) + (int)$fromIndex;
}
if ($result === false) {
return -1;
}
return $result;
}
/**
* Picks a random element from the array
*
* @param array $array
* @return mixed A random entry or null if the array is empty
*/
public function random(iterable $array)
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
if ($array === []) {
return null;
}
$randomIndex = array_rand($array);
return $array[$randomIndex];
}
/**
* Sorts an array
*
* The sorting is done first by numbers, then by characters.
*
* Internally natsort() is used as it most closely resembles javascript's sort().
* Because there are no real associative arrays in Javascript, keys of the array will be preserved.
*
* @param iterable $array
* @return array The sorted array
*/
public function sort(iterable $array): array
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
if ($array === []) {
return $array;
}
natsort($array);
$i = 0;
$newArray = [];
foreach ($array as $key => $value) {
if (is_string($key)) {
$newArray[$key] = $value;
} else {
$newArray[$i] = $value;
$i++;
}
}
return $newArray;
}
/**
* Sort an array by key
*
* @param iterable $array The array to sort
* @return array The sorted array
*/
public function ksort(iterable $array): array
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
\ksort($array, SORT_NATURAL | SORT_FLAG_CASE);
return $array;
}
/**
* Shuffle an array
*
* Randomizes entries an array with the option to preserve the existing keys.
* When this option is set to false, all keys will be replaced
*
* @param iterable $array
* @param bool $preserveKeys Wether to preserve the keys when shuffling the array
* @return array The shuffled array
*/
public function shuffle(iterable $array, $preserveKeys = true): array
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
if ($array === []) {
return $array;
}
if ($preserveKeys) {
$keys = array_keys($array);
shuffle($keys);
$shuffledArray = [];
foreach ($keys as $key) {
$shuffledArray[$key] = $array[$key];
}
$array = $shuffledArray;
} else {
shuffle($array);
}
return $array;
}
/**
* Removes duplicate values from an array
*
* @param iterable $array The input array
* @return array The filtered array.
*/
public function unique(iterable $array): array
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
return array_unique($array);
}
/**
* Removes the last element from an array
*
* Note: This differs from the JavaScript behavior of Array.pop which will return the popped element.
*
* An empty array will result in an empty array again.
*
* @param iterable $array
* @return array The array without the last element
*/
public function pop(iterable $array): array
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
if ($array === []) {
return $array;
}
array_pop($array);
return $array;
}
/**
* Insert one or more elements at the end of an array
*
* Allows to push multiple elements at once::
*
* Array.push(array, e1, e2)
*
* @param iterable|scalar|null $array
* @param mixed $element
* @return array The array with the inserted elements
*/
public function push($array, $element): array
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
if (is_scalar($array)) {
$array = [$array];
}
if ($array === null) {
$array = [];
}
if (is_array($array) === false) {
throw new \InvalidArgumentException('$array must be of type iterable|scalar|null got: ' . gettype($array), 1647595715);
}
$elements = func_get_args();
array_shift($elements);
foreach ($elements as $element) {
array_push($array, $element);
}
return $array;
}
/**
* Remove the first element of an array
*
* Note: This differs from the JavaScript behavior of Array.shift which will return the shifted element.
*
* An empty array will result in an empty array again.
*
* @param iterable $array
* @return array The array without the first element
*/
public function shift(iterable $array): array
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
array_shift($array);
return $array;
}
/**
* Insert one or more elements at the beginning of an array
*
* Allows to insert multiple elements at once::
*
* Array.unshift(array, e1, e2)
*
* @param iterable $array
* @param mixed $element
* @return array The array with the inserted elements
*/
public function unshift(iterable $array, $element): array
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
// get all elements that are supposed to be added
$elements = func_get_args();
array_shift($elements);
foreach ($elements as $element) {
array_unshift($array, $element);
}
return $array;
}
/**
* Replaces a range of an array by the given replacements
*
* Allows to give multiple replacements at once::
*
* Array.splice(array, 3, 2, 'a', 'b')
*
* @param iterable $array
* @param int $offset Index of the first element to remove
* @param int $length Number of elements to remove
* @param mixed $replacements Elements to insert instead of the removed range
* @return array The array with removed and replaced elements
*/
public function splice(iterable $array, $offset, $length = 1, $replacements = null): array
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
$arguments = func_get_args();
$replacements = array_slice($arguments, 3);
array_splice($array, $offset, $length, $replacements);
return $array;
}
/**
* Exchanges all keys with their associated values in an array
*
* Note that the values of array need to be valid keys, i.e. they need to be either int or string.
* If a value has several occurrences, the latest key will be used as its value, and all others will be lost.
*
* @param iterable $array
* @return array The array with flipped keys and values
*/
public function flip(iterable $array): array
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
return array_flip($array);
}
/**
* Create an array containing a range of elements
*
* If a step value is given, it will be used as the increment between elements in the sequence.
* step should be given as a positive number. If not specified, step will default to 1.
*
* @param mixed $start First value of the sequence.
* @param mixed $end The sequence is ended upon reaching the end value.
* @param int $step The increment between items, will default to 1.
* @return array Array of elements from start to end, inclusive.
*/
public function range($start, $end, $step = 1): array
{
return range($start, $end, $step);
}
/**
* Set the specified key in the the array
*
* @param iterable $array
* @param string|integer $key the key that should be set
* @param mixed $value the value to assign to the key
* @return array The modified array.
*/
public function set(iterable $array, $key, $value): array
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
$array[$key] = $value;
return $array;
}
/**
* Apply the callback to each element of the array, passing each element and key as arguments
*
* Examples::
*
* Array.map([1, 2, 3, 4], x => x * x)
* Array.map([1, 2, 3, 4], (x, index) => x * index)
*
* @param iterable $array Array of elements to map
* @param callable $callback Callback to apply for each element, current value and key will be passed as arguments
* @return array The array with callback applied, keys will be preserved
*/
public function map(iterable $array, callable $callback): array
{
$result = [];
foreach ($array as $key => $element) {
$result[$key] = $callback($element, $key);
}
return $result;
}
/**
* Apply the callback to each element of the array and accumulate a single value
*
* Examples::
*
* Array.reduce([1, 2, 3, 4], (accumulator, currentValue) => accumulator + currentValue) // == 10
* Array.reduce([1, 2, 3, 4], (accumulator, currentValue) => accumulator + currentValue, 1) // == 11
*
* @param iterable $array Array of elements to reduce to a value
* @param callable $callback Callback for accumulating values, accumulator, current value and key will be passed as arguments
* @param mixed $initialValue Initial value, defaults to first item in array and callback starts with second entry
* @return mixed
*/
public function reduce(iterable $array, callable $callback, $initialValue = null)
{
$accumulator = $initialValue;
$needsAccumulator = $initialValue === null;
foreach ($array as $key => $element) {
// Lazily set the accumulator to prevent evaluation of the full array if a Traversable is given
if ($needsAccumulator) {
$accumulator = $element;
$needsAccumulator = false;
continue;
}
$accumulator = $callback($accumulator, $element, $key);
}
return $accumulator;
}
/**
* Filter an array by a test given as the callback, passing each element and key as arguments
*
* Examples:
*
* Array.filter([1, 2, 3, 4], x => x % 2 == 0) // == [2, 4]
* Array.filter(['foo', 'bar', 'baz'], (x, index) => index < 2) // == ['foo', 'bar']
*
* @param iterable $array Array of elements to filter
* @param callable $callback Callback for testing if an element should be included in the result, current value and key will be passed as arguments
* @return array The array with elements where callback returned true
*/
public function filter(iterable $array, callable $callback = null): array
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
}
if (is_null($callback)) {
return array_filter($array);
} else {
return array_filter($array, $callback, ARRAY_FILTER_USE_BOTH);
}
}
/**
* Check if at least one element in an array passes a test given by the calback,
* passing each element and key as arguments
*
* Example::
*
* Array.some([1, 2, 3, 4], x => x % 2 == 0) // == true
* Array.some([1, 2, 3, 4], x => x > 4) // == false
*
* @param iterable $array Array of elements to test
* @param callable $callback Callback for testing elements, current value and key will be passed as arguments
* @return bool True if at least one element passed the test
*/
public function some(iterable $array, callable $callback): bool
{
foreach ($array as $key => $value) {
if ($callback($value, $key)) {
return true;
}
}
return false;
}
/**
* Check if all elements in an array pass a test given by the calback,
* passing each element and key as arguments
*
* Example::
*
* Array.every([1, 2, 3, 4], x => x % 2 == 0) // == false
* Array.every([2, 4, 6, 8], x => x % 2) // == true
*
* @param iterable $array Array of elements to test
* @param callable $callback Callback for testing elements, current value and key will be passed as arguments
* @return bool True if all elements passed the test
*/
public function every(iterable $array, callable $callback): bool
{
foreach ($array as $key => $value) {
if (!$callback($value, $key)) {
return false;
}
}
return true;
}
/**
* All methods are considered safe
*
* @param string $methodName
* @return bool
*/
public function allowsCallOfMethod($methodName): bool
{
return true;
}
}