Arr::flatten()   A
last analyzed

Complexity

Conditions 4
Paths 1

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 1
nop 2
dl 0
loc 13
rs 9.2
c 0
b 0
f 0
ccs 0
cts 2
cp 0
crap 20
1
<?php
2
/**
3
 * Created by rozbo at 2017/3/19 下午5:07
4
 */
5
6
namespace puck\tools;
7
8
9
class Arr {
10
    //use Macroable;
11
12
    /**
13
     * Determine whether the given value is array accessible.
14
     *
15
     * @param  mixed $value
16
     * @return bool
17
     */
18
    public static function accessible($value) {
19
        return is_array($value) || $value instanceof ArrayAccess;
0 ignored issues
show
Bug introduced by
The class puck\tools\ArrayAccess does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
20
    }
21
22
    /**
23
     * Add an element to an array using "dot" notation if it doesn't exist.
24
     *
25
     * @param  array $array
26
     * @param  string $key
27
     * @param  mixed $value
28
     * @return array
29
     */
30
    public static function add($array, $key, $value) {
31
        if (is_null(static::get($array, $key))) {
32
            static::set($array, $key, $value);
33
        }
34
35
        return $array;
36
    }
37
38
    /**
39
     * Collapse an array of arrays into a single array.
40
     *
41
     * @param  array $array
42
     * @return array
43
     */
44
    public static function collapse($array) {
45
        $results = [];
46
47
        foreach ($array as $values) {
48
            if ($values instanceof Collection) {
0 ignored issues
show
Bug introduced by
The class puck\tools\Collection does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
49
                $values = $values->all();
50
            } elseif (!is_array($values)) {
51
                continue;
52
            }
53
54
            $results = array_merge($results, $values);
55
        }
56
57
        return $results;
58
    }
59
60
    /**
61
     * Divide an array into two arrays. One with keys and the other with values.
62
     *
63
     * @param  array $array
64
     * @return array
65
     */
66
    public static function divide($array) {
67
        return [array_keys($array), array_values($array)];
68
    }
69
70
    /**
71
     * Flatten a multi-dimensional associative array with dots.
72
     *
73
     * @param  array $array
74
     * @param  string $prepend
75
     * @return array
76
     */
77
    public static function dot($array, $prepend = '') {
78
        $results = [];
79
80
        foreach ($array as $key => $value) {
81
            if (is_array($value) && !empty($value)) {
82
                $results = array_merge($results, static::dot($value, $prepend . $key . '.'));
83
            } else {
84
                $results[$prepend . $key] = $value;
85
            }
86
        }
87
88
        return $results;
89
    }
90
91
    /**
92
     * Get all of the given array except for a specified array of items.
93
     *
94
     * @param  array $array
95
     * @param  array|string $keys
96
     * @return array
97
     */
98
    public static function except($array, $keys) {
99
        static::forget($array, $keys);
100
101
        return $array;
102
    }
103
104
    /**
105
     * Determine if the given key exists in the provided array.
106
     *
107
     * @param  \ArrayAccess|array $array
108
     * @param  string|int $key
109
     * @return bool
110
     */
111
    public static function exists($array, $key) {
112
        if ($array instanceof ArrayAccess) {
0 ignored issues
show
Bug introduced by
The class puck\tools\ArrayAccess does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
113
            return $array->offsetExists($key);
114
        }
115
116
        return array_key_exists($key, $array);
117
    }
118
119
    /**
120
     * Return the first element in an array passing a given truth test.
121
     *
122
     * @param  array $array
123
     * @param  callable|null $callback
124
     * @param  mixed $default
125
     * @return mixed
126
     */
127
    public static function first($array, callable $callback = null, $default = null) {
128
        if (is_null($callback)) {
129
            if (empty($array)) {
130
                return value($default);
131
            }
132
133
            foreach ($array as $item) {
134
                return $item;
135
            }
136
        }
137
138
        foreach ($array as $key => $value) {
139
            if (call_user_func($callback, $value, $key)) {
140
                return $value;
141
            }
142
        }
143
144
        return value($default);
145
    }
146
147
    /**
148
     * Return the last element in an array passing a given truth test.
149
     *
150
     * @param  array $array
151
     * @param  callable|null $callback
152
     * @param  mixed $default
153
     * @return mixed
154
     */
155
    public static function last($array, callable $callback = null, $default = null) {
156
        if (is_null($callback)) {
157
            return empty($array) ? value($default) : end($array);
158
        }
159
160
        return static::first(array_reverse($array, true), $callback, $default);
161
    }
162
163
    /**
164
     * Flatten a multi-dimensional array into a single level.
165
     *
166
     * @param  array $array
167
     * @param  int $depth
168
     * @return array
169
     */
170
    public static function flatten($array, $depth = INF) {
171
        return array_reduce($array, function ($result, $item) use ($depth) {
172
            $item = $item instanceof Collection ? $item->all() : $item;
0 ignored issues
show
Bug introduced by
The class puck\tools\Collection does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
173
174
            if (!is_array($item)) {
175
                return array_merge($result, [$item]);
176
            } elseif ($depth === 1) {
177
                return array_merge($result, array_values($item));
178
            } else {
179
                return array_merge($result, static::flatten($item, $depth - 1));
180
            }
181
        }, []);
182
    }
183
184
    /**
185
     * Remove one or many array items from a given array using "dot" notation.
186
     *
187
     * @param  array $array
188
     * @param  array|string $keys
189
     * @return void
190
     */
191
    public static function forget(&$array, $keys) {
192
        $original = &$array;
193
194
        $keys = (array)$keys;
195
196
        if (count($keys) === 0) {
197
            return;
198
        }
199
200
        foreach ($keys as $key) {
201
            // if the exact key exists in the top-level, remove it
202
            if (static::exists($array, $key)) {
203
                unset($array[$key]);
204
205
                continue;
206
            }
207
208
            $parts = explode('.', $key);
209
210
            // clean up before each pass
211
            $array = &$original;
212
213
            while (count($parts) > 1) {
214
                $part = array_shift($parts);
215
216
                if (isset($array[$part]) && is_array($array[$part])) {
217
                    $array = &$array[$part];
218
                } else {
219
                    continue 2;
220
                }
221
            }
222
223
            unset($array[array_shift($parts)]);
224
        }
225
    }
226
227
    /**
228
     * Get an item from an array using "dot" notation.
229
     *
230
     * @param  \ArrayAccess|array $array
231
     * @param  string $key
232
     * @param  mixed $default
233
     * @return mixed
234
     */
235
    public static function get($array, $key, $default = null) {
236
        if (!static::accessible($array)) {
237
            return value($default);
238
        }
239
240
        if (is_null($key)) {
241
            return $array;
242
        }
243
244
        if (static::exists($array, $key)) {
245
            return $array[$key];
246
        }
247
248
        foreach (explode('.', $key) as $segment) {
249
            if (static::accessible($array) && static::exists($array, $segment)) {
250
                $array = $array[$segment];
251
            } else {
252
                return value($default);
253
            }
254
        }
255
256
        return $array;
257
    }
258
259
    /**
260
     * Check if an item or items exist in an array using "dot" notation.
261
     *
262
     * @param  \ArrayAccess|array $array
263
     * @param  string|array $keys
264
     * @return bool
265
     */
266
    public static function has($array, $keys) {
267
        if (is_null($keys)) {
268
            return false;
269
        }
270
271
        $keys = (array)$keys;
272
273
        if (!$array) {
274
            return false;
275
        }
276
277
        if ($keys === []) {
278
            return false;
279
        }
280
281
        foreach ($keys as $key) {
282
            $subKeyArray = $array;
283
284
            if (static::exists($array, $key)) {
285
                continue;
286
            }
287
288
            foreach (explode('.', $key) as $segment) {
289
                if (static::accessible($subKeyArray) && static::exists($subKeyArray, $segment)) {
290
                    $subKeyArray = $subKeyArray[$segment];
291
                } else {
292
                    return false;
293
                }
294
            }
295
        }
296
297
        return true;
298
    }
299
300
    /**
301
     * Determines if an array is associative.
302
     *
303
     * An array is "associative" if it doesn't have sequential numerical keys beginning with zero.
304
     *
305
     * @param  array $array
306
     * @return bool
307
     */
308
    public static function isAssoc(array $array) {
309
        $keys = array_keys($array);
310
311
        return array_keys($keys) !== $keys;
312
    }
313
    /**
314
     * Is Array Multidim
315
     *
316
     * @access public
317
     * @param  $array
318
     *
319
     * @return boolean
320
     */
321
    public static function isMultidim($array)
322
    {
323
        if (!is_array($array)) {
324
            return false;
325
        }
326
327
        return (bool)count(array_filter($array, 'is_array'));
328
    }
329
330
    /**
331
     * Get a subset of the items from the given array.
332
     *
333
     * @param  array $array
334
     * @param  array|string $keys
335
     * @return array
336
     */
337
    public static function only($array, $keys) {
338
        return array_intersect_key($array, array_flip((array)$keys));
339
    }
340
341
    /**
342
     * Pluck an array of values from an array.
343
     *
344
     * @param  array $array
345
     * @param  string|array $value
346
     * @param  string|array|null $key
347
     * @return array
348
     */
349
    public static function pluck($array, $value, $key = null) {
350
        $results = [];
351
352
        list($value, $key) = static::explodePluckParameters($value, $key);
353
354
        foreach ($array as $item) {
355
            $itemValue = data_get($item, $value);
356
357
            // If the key is "null", we will just append the value to the array and keep
358
            // looping. Otherwise we will key the array using the value of the key we
359
            // received from the developer. Then we'll return the final array form.
360
            if (is_null($key)) {
361
                $results[] = $itemValue;
362
            } else {
363
                $itemKey = data_get($item, $key);
364
365
                $results[$itemKey] = $itemValue;
366
            }
367
        }
368
369
        return $results;
370
    }
371
372
    /**
373
     * Explode the "value" and "key" arguments passed to "pluck".
374
     *
375
     * @param  string|array $value
376
     * @param  string|array|null $key
377
     * @return array
378
     */
379
    protected static function explodePluckParameters($value, $key) {
380
        $value = is_string($value) ? explode('.', $value) : $value;
381
382
        $key = is_null($key) || is_array($key) ? $key : explode('.', $key);
383
384
        return [$value, $key];
385
    }
386
387
    /**
388
     * Push an item onto the beginning of an array.
389
     *
390
     * @param  array $array
391
     * @param  mixed $value
392
     * @param  mixed $key
393
     * @return array
394
     */
395
    public static function prepend($array, $value, $key = null) {
396
        if (is_null($key)) {
397
            array_unshift($array, $value);
398
        } else {
399
            $array = [$key => $value] + $array;
400
        }
401
402
        return $array;
403
    }
404
405
    /**
406
     * Get a value from the array, and remove it.
407
     *
408
     * @param  array $array
409
     * @param  string $key
410
     * @param  mixed $default
411
     * @return mixed
412
     */
413
    public static function pull(&$array, $key, $default = null) {
414
        $value = static::get($array, $key, $default);
415
416
        static::forget($array, $key);
417
418
        return $value;
419
    }
420
421
    /**
422
     * Set an array item to a given value using "dot" notation.
423
     *
424
     * If no key is given to the method, the entire array will be replaced.
425
     *
426
     * @param  array $array
427
     * @param  string $key
428
     * @param  mixed $value
429
     * @return array
430
     */
431
    public static function set(&$array, $key, $value) {
432
        if (is_null($key)) {
433
            return $array = $value;
434
        }
435
436
        $keys = explode('.', $key);
437
438
        while (count($keys) > 1) {
439
            $key = array_shift($keys);
440
441
            // If the key doesn't exist at this depth, we will just create an empty array
442
            // to hold the next value, allowing us to create the arrays to hold final
443
            // values at the correct depth. Then we'll keep digging into the array.
444
            if (!isset($array[$key]) || !is_array($array[$key])) {
445
                $array[$key] = [];
446
            }
447
448
            $array = &$array[$key];
449
        }
450
451
        $array[array_shift($keys)] = $value;
452
453
        return $array;
454
    }
455
456
    /**
457
     * Shuffle the given array and return the result.
458
     *
459
     * @param  array $array
460
     * @return array
461
     */
462
    public static function shuffle($array) {
463
        shuffle($array);
464
465
        return $array;
466
    }
467
468
    /**
469
     * Sort the array using the given callback or "dot" notation.
470
     *
471
     * @param  array $array
472
     * @param  callable|string $callback
473
     * @return array
474
     */
475
    public static function sort($array, $callback) {
476
        return Collection::make($array)->sortBy($callback)->all();
477
    }
478
479
    /**
480
     * Recursively sort an array by keys and values.
481
     *
482
     * @param  array $array
483
     * @return array
484
     */
485
    public static function sortRecursive($array) {
486
        foreach ($array as &$value) {
487
            if (is_array($value)) {
488
                $value = static::sortRecursive($value);
489
            }
490
        }
491
492
        if (static::isAssoc($array)) {
493
            ksort($array);
494
        } else {
495
            sort($array);
496
        }
497
498
        return $array;
499
    }
500
501
    /**
502
     * Filter the array using the given callback.
503
     *
504
     * @param  array $array
505
     * @param  callable $callback
506
     * @return array
507
     */
508
    public static function where($array, callable $callback) {
509
        return array_filter($array, $callback, ARRAY_FILTER_USE_BOTH);
510
    }
511
}