| Conditions | 10 | 
| Paths | 46 | 
| Total Lines | 53 | 
| Code Lines | 30 | 
| Lines | 0 | 
| Ratio | 0 % | 
| Changes | 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 | ||
| 46 | protected function packArray(array $array, int $level = 0): string | ||
| 47 |     { | ||
| 48 |         if ($array === []) { | ||
| 49 | return '[]'; | ||
| 50 | } | ||
| 51 | |||
| 52 | //Delimiters between rows and sub-arrays. | ||
| 53 | $subIndent = "\n" . str_repeat(self::INDENT, $level + 2); | ||
| 54 | $keyIndent = "\n" . str_repeat(self::INDENT, $level + 1); | ||
| 55 | |||
| 56 | //No keys for associated array | ||
| 57 | $associated = array_diff_key($array, array_keys(array_keys($array))); | ||
| 58 | |||
| 59 | $result = []; | ||
| 60 | $innerIndent = 0; | ||
| 61 |         if (!empty($associated)) { | ||
| 62 |             foreach ($array as $key => $value) { | ||
| 63 | //Based on biggest key length | ||
| 64 | $innerIndent = max(strlen(var_export($key, true)), $innerIndent); | ||
| 65 | } | ||
| 66 | } | ||
| 67 | |||
| 68 |         foreach ($array as $key => $value) { | ||
| 69 | $prefix = ''; | ||
| 70 |             if (!empty($associated)) { | ||
| 71 | //Key prefix | ||
| 72 | $prefix = str_pad( | ||
| 73 | var_export($key, true), | ||
| 74 | $innerIndent, ' ', | ||
| 75 | STR_PAD_RIGHT | ||
| 76 | ) . " => "; | ||
| 77 | } | ||
| 78 | |||
| 79 |             if (!is_array($value)) { | ||
| 80 | $result[] = $prefix . $this->packValue($value); | ||
| 81 | continue; | ||
| 82 | } | ||
| 83 | |||
| 84 |             if ($value === []) { | ||
| 85 | $result[] = $prefix . "[]"; | ||
| 86 | continue; | ||
| 87 | } | ||
| 88 | |||
| 89 | $subArray = $this->packArray($value, $level + 1); | ||
| 90 |             $result[] = $prefix . "[{$subIndent}" . $subArray . "{$keyIndent}]"; | ||
| 91 | } | ||
| 92 | |||
| 93 |         if ($level !== 0) { | ||
| 94 |             return $result ? join(",{$keyIndent}", $result) : ""; | ||
| 95 | } | ||
| 96 | |||
| 97 |         return "[{$keyIndent}" . join(",{$keyIndent}", $result) . "\n]"; | ||
| 98 | } | ||
| 99 | |||
| 140 | } |