Conditions | 13 |
Paths | 17 |
Total Lines | 44 |
Code Lines | 24 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php |
||
72 | public static function getValueByPath(object|array $array, Closure|string $key, mixed $default = null) |
||
73 | { |
||
74 | if ($key instanceof Closure) { |
||
75 | return $key($array, $default); |
||
76 | } |
||
77 | |||
78 | if (is_array($key)) { |
||
|
|||
79 | $lastKey = array_pop($key); |
||
80 | foreach ($key as $keyPart) { |
||
81 | $array = static::getValueByPath($array, $keyPart); |
||
82 | } |
||
83 | $key = $lastKey ?? ''; |
||
84 | } |
||
85 | |||
86 | if (is_object($array) && property_exists($array, $key)) { |
||
87 | return $array->$key; |
||
88 | } |
||
89 | if (static::keyExists($key, $array)) { |
||
90 | return $array[$key]; |
||
91 | } |
||
92 | |||
93 | if ($key && ($pos = strrpos($key, '.')) !== false) { |
||
94 | $array = static::getValueByPath($array, substr($key, 0, $pos), $default); |
||
95 | $key = substr($key, $pos + 1); |
||
96 | } |
||
97 | |||
98 | if (is_object($array)) { |
||
99 | // this is expected to fail if the property does not exist, or __get() is not implemented |
||
100 | // it is not reliably possible to check whether a property is accessible beforehand |
||
101 | try { |
||
102 | return $array->$key; |
||
103 | } catch (\Exception $e) { |
||
104 | if ($array instanceof ArrayAccess) { |
||
105 | return $default; |
||
106 | } |
||
107 | throw $e; |
||
108 | } |
||
109 | } |
||
110 | |||
111 | if (static::keyExists($key, $array)) { |
||
112 | return $array[$key]; |
||
113 | } |
||
114 | |||
115 | return $default; |
||
116 | } |
||
118 |