| 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 |
||
| 76 | public static function getValueByPath(object|array $array, Closure|string $key, mixed $default = null) |
||
| 77 | { |
||
| 78 | if ($key instanceof Closure) { |
||
| 79 | return $key($array, $default); |
||
| 80 | } |
||
| 81 | |||
| 82 | if (is_array($key)) { |
||
|
|
|||
| 83 | $lastKey = array_pop($key); |
||
| 84 | foreach ($key as $keyPart) { |
||
| 85 | $array = static::getValueByPath($array, $keyPart); |
||
| 86 | } |
||
| 87 | $key = $lastKey ?? ''; |
||
| 88 | } |
||
| 89 | |||
| 90 | if (is_object($array) && property_exists($array, $key)) { |
||
| 91 | return $array->$key; |
||
| 92 | } |
||
| 93 | if (static::keyExists($key, $array)) { |
||
| 94 | return $array[$key]; |
||
| 95 | } |
||
| 96 | |||
| 97 | if ($key && ($pos = strrpos($key, '.')) !== false) { |
||
| 98 | $array = static::getValueByPath($array, substr($key, 0, $pos), $default); |
||
| 99 | $key = substr($key, $pos + 1); |
||
| 100 | } |
||
| 101 | |||
| 102 | if (is_object($array)) { |
||
| 103 | // this is expected to fail if the property does not exist, or __get() is not implemented |
||
| 104 | // it is not reliably possible to check whether a property is accessible beforehand |
||
| 105 | try { |
||
| 106 | return $array->$key; |
||
| 107 | } catch (\Exception $e) { |
||
| 108 | if ($array instanceof ArrayAccess) { |
||
| 109 | return $default; |
||
| 110 | } |
||
| 111 | throw $e; |
||
| 112 | } |
||
| 113 | } |
||
| 114 | |||
| 115 | if (static::keyExists($key, $array)) { |
||
| 116 | return $array[$key]; |
||
| 117 | } |
||
| 118 | |||
| 119 | return $default; |
||
| 120 | } |
||
| 122 |