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