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