Completed
Pull Request — master (#24)
by Alexander
01:53
created

ArrayManipulations   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 56
rs 10
c 0
b 0
f 0
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getFromArrayByKey() 0 7 2
B getArrayValueByKeys() 0 13 5
1
<?php
2
3
namespace alkemann\h2l\util;
4
5
use OutOfBoundsException;
6
7
/**
8
 * Class Util
9
 *
10
 * @package alkemann\h2l
11
 */
12
class ArrayManipulations
13
{
14
    /**
15
     * Look for a deeo value in a nested data array.
16
     *
17
     * Given $data = ['one' => ['two' => ['three' => 55]], 'four' => []];
18
     *
19
     * ```php
20
     *  getFromArrayByKey('one.two.three', $data) -> 55
21
     *  getFromArrayByKey('one|two', $data, '|') -> ['three' => 55]
22
     *  getFromArrayByKey('four.five', $data) -> throws OutOfBoundsException
23
     * ```
24
     *
25
     * @param string $key
26
     * @param array $data
27
     * @param string $delimiter
28
     * @return mixed|null
29
     */
30
    public static function getFromArrayByKey(string $key, array $data, string $delimiter = '.')
31
    {
32
        $keys = explode($delimiter, $key);
33
        try {
34
            return self::getArrayValueByKeys($keys, $data);
35
        } catch (\OutOfBoundsException $e) {
36
            return null;
37
        }
38
    }
39
40
    /**
41
     * Look for a deep value in a data array.
42
     *
43
     * Given $data = ['one' => ['two' => ['three' => 55]], 'four' => []];
44
     *
45
     * ```php
46
     *  getArrayValueByKeys(['one','two','three'], $data) will return 55
47
     *  getArrayValueByKeys(['four','five'], $data) will throw OutOfBoundsException
48
     * ```
49
     *
50
     * @param  mixed $keys
51
     * @param  mixed $data passed by reference
52
     * @return mixed
53
     * @throws OutOfBoundsException if the key does not exist in data
54
     */
55
    public static function getArrayValueByKeys(array $keys, &$data)
56
    {
57
        $key = array_shift($keys);
58
        if (!is_array($data) || empty($key)) {
59
            return $data;
60
        }
61
        if (array_key_exists($key, $data) === false) {
62
            throw new OutOfBoundsException("Key [" . join('.', $keys) . ".$key] not set in " . print_r($data, 1));
63
        }
64
        if (empty($keys)) {
65
            return $data[$key];
66
        } else {
67
            return self::getArrayValueByKeys($keys, $data[$key]);
68
        }
69
    }
70
}
71