Test Failed
Pull Request — master (#12)
by wujunze
03:09
created

ArrayHelper   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 23
c 1
b 0
f 1
dl 0
loc 58
rs 10
wmc 16

2 Methods

Rating   Name   Duplication   Size   Complexity  
A remove() 0 10 4
C getValue() 0 32 12
1
<?php
2
declare(strict_types=1);
3
4
namespace Seasx\SeasLogger;
5
6
use Closure;
7
8
/**
9
 * Class ArrayHelper
10
 * @package Seasx\SeasLogger
11
 */
12
class ArrayHelper
13
{
14
    /**
15
     * @param $array
16
     * @param $key
17
     * @param null $default
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $default is correct as it would always require null to be passed?
Loading history...
18
     * @return mixed|null
19
     */
20
    public static function getValue($array, $key, $default = null)
21
    {
22
        if ($key instanceof Closure) {
23
            return $key($array, $default);
24
        }
25
26
        if (is_array($key)) {
27
            $lastKey = array_pop($key);
28
            foreach ($key as $keyPart) {
29
                $array = static::getValue($array, $keyPart);
30
            }
31
            $key = $lastKey;
32
        }
33
34
        if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) {
35
            return $array[$key];
36
        }
37
38
        if (($pos = strrpos($key, '.')) !== false) {
39
            $array = static::getValue($array, substr($key, 0, $pos), $default);
40
            $key = substr($key, $pos + 1);
41
        }
42
43
        if (is_object($array)) {
44
            // this is expected to fail if the property does not exist, or __get() is not implemented
45
            // it is not reliably possible to check whether a property is accessible beforehand
46
            return $array->$key;
47
        } elseif (is_array($array)) {
48
            return (isset($array[$key]) || array_key_exists($key, $array)) ? $array[$key] : $default;
49
        }
50
51
        return $default;
52
    }
53
54
    /**
55
     * @param $array
56
     * @param $key
57
     * @param null $default
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $default is correct as it would always require null to be passed?
Loading history...
58
     * @return mixed|null
59
     */
60
    public static function remove(&$array, $key, $default = null)
61
    {
62
        if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) {
63
            $value = $array[$key];
64
            unset($array[$key]);
65
66
            return $value;
67
        }
68
69
        return $default;
70
    }
71
}
72