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