1: <?php
2: /**
3: * This file is part of the Autarky package.
4: *
5: * (c) Andreas Lutro <anlutro@gmail.com>
6: *
7: * For the full copyright and license information, please view the LICENSE
8: * file that was distributed with this source code.
9: */
10:
11: namespace Autarky\Utils;
12:
13: /**
14: * Array utility functions.
15: */
16: class ArrayUtil
17: {
18: /**
19: * This class is a static class and should not be instantiated.
20: */
21: private function __construct()
22: {
23: //
24: }
25:
26: /**
27: * Get an element from an array.
28: *
29: * @param array $data
30: * @param string $key Specify a nested element by separating keys with full stops.
31: * @param mixed $default If the element is not found, return this.
32: *
33: * @return mixed
34: */
35: public static function get(array $data, $key, $default = null)
36: {
37: if ($key === null) {
38: return $data;
39: }
40:
41: foreach (explode('.', $key) as $segment) {
42: if (!is_array($data)) {
43: return $default;
44: }
45:
46: if (!array_key_exists($segment, $data)) {
47: return $default;
48: }
49:
50: $data = $data[$segment];
51: }
52:
53: return $data;
54: }
55:
56: /**
57: * Determine if an array has a given key.
58: *
59: * @param array $data
60: * @param string $key
61: *
62: * @return boolean
63: */
64: public static function has(array $data, $key)
65: {
66: foreach (explode('.', $key) as $segment) {
67: if (!is_array($data)) {
68: return false;
69: }
70:
71: if (!array_key_exists($segment, $data)) {
72: return false;
73: }
74:
75: $data = $data[$segment];
76: }
77:
78: return true;
79: }
80:
81: /**
82: * Set an element of an array.
83: *
84: * @param array $data
85: * @param string $key Specify a nested element by separating keys with full stops.
86: * @param mixed $value
87: */
88: public static function set(array &$data, $key, $value)
89: {
90: $segments = explode('.', $key);
91:
92: $key = array_pop($segments);
93:
94: // iterate through all of $segments except the last one
95: foreach ($segments as $segment) {
96: if (!array_key_exists($segment, $data)) {
97: $data[$segment] = [];
98: } else if (!is_array($data[$segment])) {
99: throw new \UnexpectedValueException('Non-array segment encountered');
100: }
101:
102: $data =& $data[$segment];
103: }
104:
105: $data[$key] = $value;
106: }
107: }
108: