-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathArrayUtils.php
More file actions
701 lines (620 loc) · 19.2 KB
/
ArrayUtils.php
File metadata and controls
701 lines (620 loc) · 19.2 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
<?php
/**
* This file is part of the Cloudinary PHP package.
*
* (c) Cloudinary
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cloudinary;
use ArrayObject;
/**
* Class ArrayUtils
*
* @internal
*/
class ArrayUtils
{
/**
* Applies the callback to the elements of the given associative array
*
* @param callable $callback The callback function
* @param ArrayObject<int|string, mixed>|array $array An array to run through the callback function.
*
* @return array Resulting array
*/
public static function mapAssoc(callable $callback, ArrayObject|array $array): array
{
$r = [];
foreach ($array as $key => $value) {
$r[$key] = $callback($key, $value);
}
return $r;
}
/**
* Joins associative array keys and values.
*
* @param array|mixed $array An array to join
* @param string $outer Outer delimiter (between pairs)
* @param string|null $inner Inner delimiter (between key and value), if not provided $outer is used
*
* @return string|null Resulting string
*/
public static function implodeAssoc(mixed $array, string $outer = '', ?string $inner = null): ?string
{
if (! is_array($array)) {
return $array === null ? null : (string)$array;
}
if ($inner === null) {
$inner = $outer;
}
if (self::isAssoc($array)) { // implode key-value pairs using inner
$array = self::mapAssoc(
static function ($k, $v) use ($inner) {
if (! self::safeFilterFunc($v)) {
return null;
}
return self::implodeFiltered($inner, [$k, $v]);
},
$array
);
}
return self::implodeFiltered($outer, self::safeFilter($array));
}
/**
* Safe version of ArrayUtils::implodeAssoc.
*
* In addition, escapes appearances of the delimiters inside strings.
*
* @param array|mixed $array An array to join
* @param string $outer Outer delimiter (between pairs)
* @param string|null $inner Inner delimiter (between key and value), if not provided $outer is used
* @param bool $innerIsSafe Whether to omit escaping of the inner delimiter
*
*
* @see ArrayUtils::implodeAssoc
*/
public static function safeImplodeAssoc(
mixed $array,
string $outer = '',
?string $inner = null,
bool $innerIsSafe = false
): ?string {
if (! is_array($array)) {
return $array === null ? null : (string)$array;
}
if ($inner === null) {
$inner = $outer;
}
if (self::isAssoc($array)) { // implode key-value pairs using inner
$array = self::mapAssoc(
static function ($k, $v) use ($inner, $innerIsSafe) {
if ($innerIsSafe) {
return self::implodeFiltered($inner, [$k, $v]);
}
return self::escapedImplode($inner, [$k, $v]);
},
$array
);
}
return self::escapedImplode($outer, self::safeFilter($array));
}
/**
* Shortcut helper
*
* Strange signature comes from the built-in implode function that has a similar signature.
*
*
* @return string The resulting string
*
* @internal
*
* @see implode
*/
public static function implodeFiltered(
array|string $glue,
array|null $pieces,
callable|null $filterCallback = null,
int $flag = 0
): string {
$filterCallback ??= fn($value) => ArrayUtils::safeFilterFunc($value);
return self::safeImplode($glue, self::safeFilter($pieces, $filterCallback, $flag));
}
/**
* Safe version of implode.
*
* In addition, fixes serialisation of float values.
*
*/
public static function safeImplode(array|string $glue, array|null $pieces): string
{
if (! is_null($pieces)) {
array_walk(
$pieces,
static function (&$value) {
$value = TransformationUtils::floatToString($value);
}
);
}
return implode($glue, $pieces);
}
/**
* Implodes array values with escaping the glue character.
*
*/
public static function escapedImplode(string|array $glue, array|null $pieces): string
{
if (is_null($pieces)) {
return '';
}
return implode(
$glue,
array_map(
static fn($value) => StringUtils::escapeUnsafeChars($value, $glue),
$pieces
)
);
}
/**
* Uses "strlen()" instead of "empty()" to indicate whether value is considered empty.
*
* Used to keep falsy values, like 0, '0', etc.
*
* @param mixed|array $value The value to filter
*
*
* @see strlen
* @see empty
*/
protected static function safeFilterFunc(mixed $value): bool|int
{
if (is_array($value)) {
foreach ($value as $val) {
if (self::safeFilterFunc($val)) {
return true;
}
}
return false;
}
if (is_null($value)) {
return 0;
}
return strlen($value);
}
/**
* Safe version of the "array_filter" function.
*
* Uses "strlen" filter function by default, which treats non-null values (e.g. 0, false, etc) as non-empty.
*
* @see array_filter
* @see strlen
*/
public static function safeFilter(
?array $input,
callable|null $callback = null,
int $flag = 0
): ?array {
$callback ??= fn($value) => ArrayUtils::safeFilterFunc($value);
return is_null($input) ? $input : array_filter($input, $callback, $flag);
}
/**
* Sorts associative array $array keys using order defined in $orderArray.
*
* In case some of the missing/extra keys, the keys are sorted using alphabetic order. Ordered keys come first.
*
* @param ?array $array The associate array to order.
* @param array $orderArray The desired order of the keys.
*
*/
public static function sortByArray(?array $array, array $orderArray = []): ?array
{
if (! is_array($array)) {
return $array;
}
ksort($array);
return array_replace(array_intersect_key(array_flip($orderArray), $array), $array);
}
/**
* Commonly used util for building Cloudinary URL
*
*
* @return string The resulting string
*
* @internal
*/
public static function implodeUrl(array $urlParts): string
{
return self::implodeFiltered('/', $urlParts);
}
/**
* Commonly used util for building transformation URL
*
* @return string The resulting string
*
* @internal
*/
public static function implodeActionQualifiers(mixed ...$qualifiers): string
{
$serializedQualifiers = [];
foreach ($qualifiers as $item) {
$serializedQualifiers[] = (string)$item;
}
sort($serializedQualifiers);
return self::implodeFiltered(',', $serializedQualifiers);
}
/**
* Commonly used util for building transformation URL
*
* @param array $qualifierValues
*
* @return string The resulting string
*
* @internal
*/
public static function implodeQualifierValues(...$qualifierValues): string
{
return self::implodeFiltered(':', $qualifierValues);
}
/**
* Gets a key from an array if exists, otherwise returns default.
*
* @param mixed $array The data array.
* @param int|array|string $key The key. Can be a simple key(string|int), an index array that allows accessing
* nested values
* @param mixed|null $default The default value for the case when the key is not found.
*
*/
public static function get(mixed $array, int|array|string $key, mixed $default = null): mixed
{
if (is_array($key)) {
$currLevel = &$array;
foreach ($key as $currKey) {
if (! is_array($currLevel) || ! array_key_exists($currKey, $currLevel)) { //not found
return $default;
}
$currLevel = $currLevel[$currKey];
}
return $currLevel;
}
if (is_array($array) && array_key_exists($key, $array)) {
return $array[$key];
}
if ($array instanceof ArrayObject && $array->offsetExists($key)) {
return $array[$key];
}
return $default;
}
/**
* Pops a key from an array if exists, otherwise returns default
*
* @param array $array Data array
* @param int|string $key A simple key(string|int)
* @param mixed|null $default Default value for the case when key is not found
*
*/
public static function pop(array &$array, int|string $key, mixed $default = null): mixed
{
$val = self::get($array, $key, $default);
unset($array[$key]);
return $val;
}
/**
* Returns a subset of associative array whitelisted by an array of keys
*
* @param ?array $array Source array (associative or not)
* @param array $keys Simple array of keys to keep
*
* @return ?array Resulting array
*/
public static function whitelist(?array $array, array $keys): ?array
{
// When providing non array(for example null), return it as is
if (! is_array($array)) {
return $array;
}
if (self::isAssoc($array)) {
return array_intersect_key($array, array_flip($keys));
}
return array_intersect($array, $keys);
}
/**
* Returns a subset of associative array with excluded keys specified by an array of keys
*
* @param ?array $array Source array (associative or not)
* @param array $blacklistedKeys Simple array of keys to be excluded
*
* @return ?array Resulting array
*/
public static function blacklist(?array $array, array $blacklistedKeys): ?array
{
// When providing non array (for example null), return it as is
if (! is_array($array)) {
return $array;
}
if (self::isAssoc($array)) {
return array_diff_key($array, array_flip($blacklistedKeys));
}
return array_diff($array, $blacklistedKeys);
}
/**
* Wraps a $value with an array, if not already an array.
*
* @param mixed $value The input value to wrap
*
*/
public static function build(mixed $value): array
{
if ($value === null) {
return [];
}
if (is_array($value) && ! self::isAssoc($value)) {
return $value;
}
return [$value];
}
/**
* Returns the first item value from the array in case it has only 1 element.
*
* It is the opposite of ArrayUtils::build function.
*
* @param mixed $array Input array
*
* @param bool $onlyAssoc Set to true to flatten only associative arrays
*
*
* @see ArrayUtils::build
*/
public static function flatten(mixed $array, bool $onlyAssoc = false): array|string|null
{
if (empty($array) || ! is_array($array) || count($array) > 1 || $onlyAssoc && ! self::isAssoc($array[0])) {
return $array;
}
return $array[0];
}
/**
* Determines whether an array is associative or not
*
* @param mixed $array Input array
*
* @return bool true if associative, otherwise false
*/
public static function isAssoc(mixed $array): bool
{
if (! is_array($array)) {
return false;
}
return $array !== array_values($array);
}
/**
* Prepends associative element to the beginning of an array.
*
* @param array $arr The input array.
* @param mixed $key The prepended key.
* @param mixed $val The prepended value.
*
* @return array The resulting array.
*
* @internal
*/
public static function prependAssoc(array &$arr, mixed $key, mixed $val): array
{
$arr = array_reverse($arr, true);
$arr[$key] = $val;
$arr = array_reverse($arr, true);
return $arr;
}
/**
* Appends element at the end of an array if not empty
*
* @param array $arr The input array.
* @param mixed $val The appended value
*
* @return array The resulting array
*
* @internal
*
*/
public static function appendNonEmpty(array &$arr, mixed $val): array
{
if (! empty($val)) {
$arr [] = $val;
}
return $arr;
}
/**
* Adds key-value pair to the associative array if the value is not empty
*
* @param array $arr The input array.
* @param int|string|null $key The key.
* @param mixed $val The appended value.
*
* @return array The resulting array
*
* @internal
*/
public static function addNonEmpty(array &$arr, int|string|null $key, mixed $val): array
{
if (! empty($val) || is_int($val) || is_float($val) || is_bool($val)) {
$arr[$key] = $val;
}
return $arr;
}
/**
* Adds key-value pair to the associative array where value is taken from source array using the same key.
*
* @param array & $resultingArr The target array.
* @param mixed $key The key to add
* @param array|ArrayObject<int|string, mixed> $sourceArray The source array
* @param mixed|null $defaultValue Fallback value, in case the key does not exist or is
* empty
*
* @return array The resulting array
*
* @internal
*/
public static function addNonEmptyFromOther(
array &$resultingArr,
mixed $key,
array|ArrayObject $sourceArray,
mixed $defaultValue = null
): array {
return self::addNonEmpty($resultingArr, $key, self::get($sourceArray, $key, $defaultValue));
}
/**
* Merges non empty array values
*
* @param array[] $arrays The arrays to merge
*
* @return array The resulting array
*
* @internal
*
*/
public static function mergeNonEmpty(...$arrays): array
{
$result = [];
foreach ($arrays as $array) {
if (! empty($array)) {
$filtered = self::safeFilter($array);
if ($filtered) {
$result = array_merge($result, $filtered);
}
}
}
return $result;
}
/**
* Inserts item to the array next to (before/after) specified key
*
* @param array $array The input array
* @param mixed $searchKey The key to search for in the array
* @param mixed $insertKey New key to insert
* @param mixed $insertValue New value for the key
* @param bool $insertAfter Whether to insert after the $searchKey
* @param bool $appendIfNotFound Whether append a new key-value pair at the end of the array in case $searchKey
* was not found
*
* @return array The new array with the inserted key
*/
public static function insertAt(
array $array,
mixed $searchKey,
mixed $insertKey,
mixed $insertValue,
bool $insertAfter = true,
bool $appendIfNotFound = true
): array {
$result = [];
foreach ($array as $key => $value) {
if ($key === $searchKey && ! $insertAfter) {
$result[$insertKey] = $insertValue;
}
$result[$key] = $value;
if ($key === $searchKey && $insertAfter) {
$result[$insertKey] = $insertValue;
}
}
if ($appendIfNotFound && count($array) === count($result)) {
$result[$insertKey] = $insertValue;
}
return $result;
}
/**
* Sets the $defaultValue in case the $key does not exist or empty.
*
* @param array $array The input array.
* @param mixed $key The key.
* @param mixed $defaultValue The default value.
*/
public static function setDefaultValue(array &$array, mixed $key, mixed $defaultValue): void
{
if (! isset($array[$key]) || ! self::safeFilterFunc($array[$key])) {
$array[$key] = $defaultValue;
}
}
/**
* Inverts simple array (indexed by int) value and sets value to null, the rest leaves as is
*
* @param array $array The input array.
*
* @return array The resulting array.
*
* @internal
*/
public static function convertToAssoc(array $array): array
{
$result = [];
foreach ($array as $k => $v) {
if (is_int($k)) {
$k = $v;
$v = null;
}
$result[$k] = $v;
}
return $result;
}
/**
* Helper function for making a recursive array copy while cloning objects on the way.
*
* @param mixed $array Source array
*
* @return mixed Recursive copy of the source array
*/
public static function deepCopy(mixed $array): mixed
{
if (! is_array($array)) {
return $array;
}
$result = [];
foreach ($array as $key => $val) {
if (is_array($val)) {
$result[$key] = self::deepCopy($val);
} elseif (is_object($val)) {
$result[$key] = clone $val;
} else {
$result[$key] = $val;
}
}
return $result;
}
/**
* Indicates whether all parameters are non-empty
*/
public static function all(array ...$params): bool
{
foreach ($params as $param) {
if (empty($param)) {
return false;
}
}
return true;
}
/**
* Case-insensitive version of in_array
*
* @param mixed $needle The searched value.
* @param array $haystack The array.
*
*/
public static function inArrayI(mixed $needle, array $haystack): bool
{
return in_array(strtolower($needle), array_map('strtolower', $haystack));
}
/**
* Walks the array and converts all booleans to string representations of their int values
*
* true becomes '1', false becomes '0'
*
* @param array &$array The input array to convert.
*/
public static function convertBoolToIntStrings(array &$array): void
{
array_walk(
$array,
static function (&$value) {
$value = TransformationUtils::boolToIntString($value);
}
);
}
}