blob: 8fa87a2b37573dfcfbf98f9a8c32c4b295c1fe65 [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
3namespace LdapRecord\Support;
4
5use ArrayAccess;
6
7class Arr
8{
9 /**
10 * Determine whether the given value is array accessible.
11 *
12 * @param mixed $value
13 *
14 * @return bool
15 */
16 public static function accessible($value)
17 {
18 return is_array($value) || $value instanceof ArrayAccess;
19 }
20
21 /**
22 * Determine if the given key exists in the provided array.
23 *
24 * @param \ArrayAccess|array $array
25 * @param string|int $key
26 *
27 * @return bool
28 */
29 public static function exists($array, $key)
30 {
31 if ($array instanceof ArrayAccess) {
32 return $array->offsetExists($key);
33 }
34
35 return array_key_exists($key, $array);
36 }
37
38 /**
39 * If the given value is not an array and not null, wrap it in one.
40 *
41 * @param mixed $value
42 *
43 * @return array
44 */
45 public static function wrap($value)
46 {
47 if (is_null($value)) {
48 return [];
49 }
50
51 return is_array($value) ? $value : [$value];
52 }
53
54 /**
55 * Return the first element in an array passing a given truth test.
56 *
57 * @param iterable $array
58 * @param callable|null $callback
59 * @param mixed $default
60 *
61 * @return mixed
62 */
63 public static function first($array, callable $callback = null, $default = null)
64 {
65 if (is_null($callback)) {
66 if (empty($array)) {
67 return Helpers::value($default);
68 }
69
70 foreach ($array as $item) {
71 return $item;
72 }
73 }
74
75 foreach ($array as $key => $value) {
76 if ($callback($value, $key)) {
77 return $value;
78 }
79 }
80
81 return Helpers::value($default);
82 }
83
84 /**
85 * Return the last element in an array passing a given truth test.
86 *
87 * @param array $array
88 * @param callable|null $callback
89 * @param mixed $default
90 *
91 * @return mixed
92 */
93 public static function last($array, callable $callback = null, $default = null)
94 {
95 if (is_null($callback)) {
96 return empty($array) ? Helpers::value($default) : end($array);
97 }
98
99 return static::first(array_reverse($array, true), $callback, $default);
100 }
101
102 /**
103 * Get an item from an array using "dot" notation.
104 *
105 * @param ArrayAccess|array $array
106 * @param string|int|null $key
107 * @param mixed $default
108 *
109 * @return mixed
110 */
111 public static function get($array, $key, $default = null)
112 {
113 if (! static::accessible($array)) {
114 return Helpers::value($default);
115 }
116
117 if (is_null($key)) {
118 return $array;
119 }
120
121 if (static::exists($array, $key)) {
122 return $array[$key];
123 }
124
125 if (strpos($key, '.') === false) {
126 return $array[$key] ?? Helpers::value($default);
127 }
128
129 foreach (explode('.', $key) as $segment) {
130 if (static::accessible($array) && static::exists($array, $segment)) {
131 $array = $array[$segment];
132 } else {
133 return Helpers::value($default);
134 }
135 }
136
137 return $array;
138 }
139}