| Conditions | 11 |
| Paths | 9 |
| Total Lines | 35 |
| Code Lines | 17 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 2 | ||
| Bugs | 1 | 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 |
||
| 54 | public static function getValueByPath(object|array $array, Closure|string $key, mixed $default = null) |
||
| 55 | { |
||
| 56 | if ($key instanceof Closure) { |
||
| 57 | return $key($array, $default); |
||
| 58 | } |
||
| 59 | |||
| 60 | if (is_object($array) && property_exists($array, $key)) { |
||
|
|
|||
| 61 | return $array->$key; |
||
| 62 | } |
||
| 63 | |||
| 64 | if (is_array($array) && array_key_exists($key, $array)) { |
||
| 65 | return $array[$key]; |
||
| 66 | } |
||
| 67 | |||
| 68 | if ($key && ($pos = strrpos($key, '.')) !== false) { |
||
| 69 | /** @psalm-var array<string, mixed>|object $array */ |
||
| 70 | $array = static::getValueByPath($array, substr($key, 0, $pos), $default); |
||
| 71 | $key = substr($key, $pos + 1); |
||
| 72 | } |
||
| 73 | |||
| 74 | if (is_object($array)) { |
||
| 75 | // this is expected to fail if the property does not exist, or __get() is not implemented |
||
| 76 | // it is not reliably possible to check whether a property is accessible beforehand |
||
| 77 | try { |
||
| 78 | return $array->$key; |
||
| 79 | } catch (\Exception $e) { |
||
| 80 | throw $e; |
||
| 81 | } |
||
| 82 | } |
||
| 83 | |||
| 84 | if (array_key_exists($key, $array)) { |
||
| 85 | return $array[$key]; |
||
| 86 | } |
||
| 87 | |||
| 88 | return $default; |
||
| 89 | } |
||
| 91 |