Passed
Push — master ( 34a83f...053766 )
by kill
03:49
created

Arr::has()   D

Complexity

Conditions 9
Paths 7

Size

Total Lines 33
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 0
Metric Value
cc 9
eloc 18
nc 7
nop 2
dl 0
loc 33
rs 4.909
c 0
b 0
f 0
ccs 0
cts 17
cp 0
crap 90
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
    /**
315
     * Get a subset of the items from the given array.
316
     *
317
     * @param  array $array
318
     * @param  array|string $keys
319
     * @return array
320
     */
321
    public static function only($array, $keys) {
322
        return array_intersect_key($array, array_flip((array)$keys));
323
    }
324
325
    /**
326
     * Pluck an array of values from an array.
327
     *
328
     * @param  array $array
329
     * @param  string|array $value
330
     * @param  string|array|null $key
331
     * @return array
332
     */
333
    public static function pluck($array, $value, $key = null) {
334
        $results = [];
335
336
        list($value, $key) = static::explodePluckParameters($value, $key);
337
338
        foreach ($array as $item) {
339
            $itemValue = data_get($item, $value);
340
341
            // If the key is "null", we will just append the value to the array and keep
342
            // looping. Otherwise we will key the array using the value of the key we
343
            // received from the developer. Then we'll return the final array form.
344
            if (is_null($key)) {
345
                $results[] = $itemValue;
346
            } else {
347
                $itemKey = data_get($item, $key);
348
349
                $results[$itemKey] = $itemValue;
350
            }
351
        }
352
353
        return $results;
354
    }
355
356
    /**
357
     * Explode the "value" and "key" arguments passed to "pluck".
358
     *
359
     * @param  string|array $value
360
     * @param  string|array|null $key
361
     * @return array
362
     */
363
    protected static function explodePluckParameters($value, $key) {
364
        $value = is_string($value) ? explode('.', $value) : $value;
365
366
        $key = is_null($key) || is_array($key) ? $key : explode('.', $key);
367
368
        return [$value, $key];
369
    }
370
371
    /**
372
     * Push an item onto the beginning of an array.
373
     *
374
     * @param  array $array
375
     * @param  mixed $value
376
     * @param  mixed $key
377
     * @return array
378
     */
379
    public static function prepend($array, $value, $key = null) {
380
        if (is_null($key)) {
381
            array_unshift($array, $value);
382
        } else {
383
            $array = [$key => $value] + $array;
384
        }
385
386
        return $array;
387
    }
388
389
    /**
390
     * Get a value from the array, and remove it.
391
     *
392
     * @param  array $array
393
     * @param  string $key
394
     * @param  mixed $default
395
     * @return mixed
396
     */
397
    public static function pull(&$array, $key, $default = null) {
398
        $value = static::get($array, $key, $default);
399
400
        static::forget($array, $key);
401
402
        return $value;
403
    }
404
405
    /**
406
     * Set an array item to a given value using "dot" notation.
407
     *
408
     * If no key is given to the method, the entire array will be replaced.
409
     *
410
     * @param  array $array
411
     * @param  string $key
412
     * @param  mixed $value
413
     * @return array
414
     */
415
    public static function set(&$array, $key, $value) {
416
        if (is_null($key)) {
417
            return $array = $value;
418
        }
419
420
        $keys = explode('.', $key);
421
422
        while (count($keys) > 1) {
423
            $key = array_shift($keys);
424
425
            // If the key doesn't exist at this depth, we will just create an empty array
426
            // to hold the next value, allowing us to create the arrays to hold final
427
            // values at the correct depth. Then we'll keep digging into the array.
428
            if (!isset($array[$key]) || !is_array($array[$key])) {
429
                $array[$key] = [];
430
            }
431
432
            $array = &$array[$key];
433
        }
434
435
        $array[array_shift($keys)] = $value;
436
437
        return $array;
438
    }
439
440
    /**
441
     * Shuffle the given array and return the result.
442
     *
443
     * @param  array $array
444
     * @return array
445
     */
446
    public static function shuffle($array) {
447
        shuffle($array);
448
449
        return $array;
450
    }
451
452
    /**
453
     * Sort the array using the given callback or "dot" notation.
454
     *
455
     * @param  array $array
456
     * @param  callable|string $callback
457
     * @return array
458
     */
459
    public static function sort($array, $callback) {
460
        return Collection::make($array)->sortBy($callback)->all();
461
    }
462
463
    /**
464
     * Recursively sort an array by keys and values.
465
     *
466
     * @param  array $array
467
     * @return array
468
     */
469
    public static function sortRecursive($array) {
470
        foreach ($array as &$value) {
471
            if (is_array($value)) {
472
                $value = static::sortRecursive($value);
473
            }
474
        }
475
476
        if (static::isAssoc($array)) {
477
            ksort($array);
478
        } else {
479
            sort($array);
480
        }
481
482
        return $array;
483
    }
484
485
    /**
486
     * Filter the array using the given callback.
487
     *
488
     * @param  array $array
489
     * @param  callable $callback
490
     * @return array
491
     */
492
    public static function where($array, callable $callback) {
493
        return array_filter($array, $callback, ARRAY_FILTER_USE_BOTH);
494
    }
495
}