Passed
Push — master ( e7e3c4...d0e289 )
by Rogier
01:26
created

Arr::accessible()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Rogierw\RwAcme\Support;
4
5
use ArrayAccess;
6
7
class Arr
8
{
9
    public static function accessible($value)
10
    {
11
        return is_array($value) || $value instanceof ArrayAccess;
12
    }
13
14
    public static function exists($array, $key)
15
    {
16
        if ($array instanceof ArrayAccess) {
17
            return $array->offsetExists($key);
18
        }
19
20
        return array_key_exists($key, $array);
21
    }
22
23
    public static function get($array, $key, $default = null)
24
    {
25
        if (!static::accessible($array)) {
26
            return value($default);
27
        }
28
29
        if (is_null($key)) {
30
            return $array;
31
        }
32
33
        if (static::exists($array, $key)) {
34
            return $array[$key];
35
        }
36
37
        if (strpos($key, '.') === false) {
38
            return $array[$key] ?? value($default);
39
        }
40
41
        foreach (explode('.', $key) as $segment) {
42
            if (static::accessible($array) && static::exists($array, $segment)) {
43
                $array = $array[$segment];
44
            } else {
45
                return value($default);
46
            }
47
        }
48
49
        return $array;
50
    }
51
52
    public static function first($array, callable $callback = null, $default = null)
53
    {
54
        if (is_null($callback)) {
55
            if (empty($array)) {
56
                return value($default);
57
            }
58
59
            foreach ($array as $item) {
60
                return $item;
61
            }
62
        }
63
64
        foreach ($array as $key => $value) {
65
            if ($callback($value, $key)) {
66
                return $value;
67
            }
68
        }
69
70
        return value($default);
71
    }
72
}
73