Conditions | 14 |
Paths | 20 |
Total Lines | 62 |
Code Lines | 39 |
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 |
||
65 | public function setMetadata(array $metadata) |
||
66 | { |
||
67 | $structuredMetadata = []; |
||
68 | |||
69 | foreach ($metadata as $property => $value) { |
||
70 | $type = gettype($value); |
||
71 | $subtype = null; |
||
72 | switch ($type) { |
||
73 | case 'boolean': |
||
74 | case 'string': |
||
75 | case 'object': |
||
76 | // Valid type |
||
77 | break; |
||
78 | |||
79 | case 'integer': |
||
80 | case 'double': |
||
81 | $type = 'number'; |
||
82 | break; |
||
83 | |||
84 | case 'array': |
||
85 | if (is_string(reset($value))) { |
||
86 | $type = 'object'; |
||
87 | break; |
||
88 | } |
||
89 | |||
90 | $subtype = gettype($value[0]); |
||
91 | array_walk($value, function ($item) use ($subtype, $property) { |
||
92 | if (gettype($item) !== $subtype) { |
||
93 | throw new \InvalidArgumentException('All array items have to be of the same type for metadata property '. $property); |
||
94 | } |
||
95 | }); |
||
96 | |||
97 | if ($subtype == 'integer' || $subtype === 'double') { |
||
98 | $subtype = 'number'; |
||
99 | } |
||
100 | $allowedSubtypes = ['boolean', 'number', 'string', 'object']; |
||
101 | if (!in_array($subtype, $allowedSubtypes)) { |
||
102 | throw new \InvalidArgumentException('Unallowed type of '. $subtype .' for array item of metadata property '. $property); |
||
103 | } |
||
104 | |||
105 | break; |
||
106 | |||
107 | default: |
||
108 | throw new \InvalidArgumentException('Unallowed type of '. $type .' for metadata property '. $property); |
||
109 | } |
||
110 | |||
111 | $metadatum = [ |
||
112 | 'name' => $property, |
||
113 | 'type' => $type, |
||
114 | 'value' => $value, |
||
115 | 'visibility' => ['api'] |
||
116 | ]; |
||
117 | |||
118 | if (isset($subtype)) { |
||
119 | $metadatum['subtype'] = $subtype; |
||
120 | } |
||
121 | |||
122 | $structuredMetadata[] = $metadatum; |
||
123 | } |
||
124 | |||
125 | $this->metadata = $structuredMetadata; |
||
126 | } |
||
127 | |||
202 |