Complex classes like Validation often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Validation, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
13 | class Validation { |
||
14 | /** |
||
15 | * @var array |
||
16 | */ |
||
17 | private $errors = []; |
||
18 | |||
19 | /** |
||
20 | * @var string |
||
21 | */ |
||
22 | private $mainMessage = ''; |
||
23 | |||
24 | /** |
||
25 | * @var int |
||
26 | */ |
||
27 | private $mainStatus = 0; |
||
28 | |||
29 | /** |
||
30 | * @var bool Whether or not fields should be translated. |
||
31 | */ |
||
32 | private $translateFieldNames = false; |
||
33 | |||
34 | /** |
||
35 | * Add an error. |
||
36 | * |
||
37 | * @param string $field The name and path of the field to add or an empty string if this is a global error. |
||
38 | * @param string $error The message code. |
||
39 | * @param int|array $options An array of additional information to add to the error entry or a numeric error code. |
||
40 | * @return $this |
||
41 | */ |
||
42 | 52 | public function addError($field, $error, $options = []) { |
|
43 | 52 | if (empty($error)) { |
|
44 | throw new \InvalidArgumentException('The error code cannot be empty.', 500); |
||
45 | } |
||
46 | |||
47 | 52 | $fieldKey = $field; |
|
48 | 52 | $row = ['field' => null, 'code' => null, 'path' => null, 'index' => null]; |
|
|
|||
49 | |||
50 | // Split the field out into a path, field, and possible index. |
||
51 | 52 | if (($pos = strrpos($field, '.')) !== false) { |
|
52 | 5 | $row['path'] = substr($field, 0, $pos); |
|
53 | 5 | $field = substr($field, $pos + 1); |
|
54 | 5 | } |
|
55 | 52 | if (preg_match('`^([^[]+)\[(\d+)\]$`', $field, $m)) { |
|
56 | 3 | $row['index'] = (int)$m[2]; |
|
57 | 3 | $field = $m[1]; |
|
58 | 3 | } |
|
59 | 52 | $row['field'] = $field; |
|
60 | 52 | $row['code'] = $error; |
|
1 ignored issue
–
show
|
|||
61 | |||
62 | $row = array_filter($row, function ($v) { |
||
63 | 52 | return $v !== null; |
|
64 | 52 | }); |
|
65 | |||
66 | 52 | if (is_array($options)) { |
|
67 | 49 | $row += $options; |
|
68 | 52 | } elseif (is_int($options)) { |
|
69 | 4 | $row['status'] = $options; |
|
70 | 4 | } |
|
71 | |||
72 | 52 | $this->errors[$fieldKey][] = $row; |
|
73 | |||
74 | 52 | return $this; |
|
75 | } |
||
76 | |||
77 | /** |
||
78 | * Get or set the error status code. |
||
79 | * |
||
80 | * The status code is an http response code and should be of the 4xx variety. |
||
81 | * |
||
82 | * @return int Returns the current status code. |
||
83 | */ |
||
84 | 45 | public function getStatus() { |
|
85 | 45 | if ($this->mainStatus) { |
|
86 | 1 | return $this->mainStatus; |
|
87 | } |
||
88 | |||
89 | 44 | if ($this->isValid()) { |
|
90 | 1 | return 200; |
|
91 | } |
||
92 | |||
93 | // There was no status so loop through the errors and look for the highest one. |
||
94 | 43 | $maxStatus = 0; |
|
95 | 43 | foreach ($this->getRawErrors() as $error) { |
|
96 | 43 | if (isset($error['status']) && $error['status'] > $maxStatus) { |
|
97 | 38 | $maxStatus = $error['status']; |
|
98 | 38 | } |
|
99 | 43 | } |
|
100 | |||
101 | 43 | return $maxStatus?: 400; |
|
102 | } |
||
103 | |||
104 | /** |
||
105 | * Get the message for this exception. |
||
106 | * |
||
107 | * @return string Returns the exception message. |
||
108 | */ |
||
109 | 46 | public function getMessage() { |
|
110 | 46 | if ($this->mainMessage) { |
|
111 | 1 | return $this->mainMessage; |
|
112 | } |
||
113 | |||
114 | 45 | $sentence = $this->translate('%s.'); |
|
115 | |||
116 | // Generate the message by concatenating all of the errors together. |
||
117 | 45 | $messages = []; |
|
118 | 45 | foreach ($this->getRawErrors() as $error) { |
|
119 | 45 | $message = $this->getErrorMessage($error); |
|
120 | 45 | if (preg_match('`\PP$`u', $message)) { |
|
121 | 2 | $message = sprintf($sentence, $message); |
|
122 | 2 | } |
|
123 | 45 | $messages[] = $message; |
|
124 | 45 | } |
|
125 | 45 | return implode(' ', $messages); |
|
126 | } |
||
127 | |||
128 | /** |
||
129 | * Gets all of the errors as a flat array. |
||
130 | * |
||
131 | * The errors are internally stored indexed by field. This method flattens them for final error returns. |
||
132 | * |
||
133 | * @return array Returns all of the errors. |
||
134 | */ |
||
135 | 4 | public function getErrors() { |
|
136 | 4 | $result = []; |
|
137 | 4 | foreach ($this->getRawErrors() as $error) { |
|
138 | 4 | $row = array_intersect_key( |
|
139 | 4 | $error, |
|
140 | 4 | ['field' => 1, 'path' => 1, 'index' => 1, 'code' => 1] |
|
141 | 4 | ); |
|
142 | |||
143 | 4 | $row['message'] = $this->getErrorMessage($error); |
|
144 | |||
145 | 4 | $result[] = $row; |
|
146 | 4 | } |
|
147 | 4 | return $result; |
|
148 | } |
||
149 | |||
150 | /** |
||
151 | * Gets all of the errors as a flat array. |
||
152 | * |
||
153 | * The errors are internally stored indexed by field. This method flattens them for final error returns. |
||
154 | * |
||
155 | * @return \Traversable Returns all of the errors. |
||
156 | */ |
||
157 | 49 | protected function getRawErrors() { |
|
158 | 49 | foreach ($this->errors as $errors) { |
|
159 | 49 | foreach ($errors as $error) { |
|
160 | 49 | yield $error; |
|
161 | 49 | } |
|
162 | 49 | } |
|
163 | 49 | } |
|
164 | |||
165 | /** |
||
166 | * Check whether or not the validation is free of errors. |
||
167 | * |
||
168 | * @return bool Returns true if there are no errors, false otherwise. |
||
169 | */ |
||
170 | 76 | public function isValid() { |
|
173 | |||
174 | /** |
||
175 | * Check whether or not a particular field is has errors. |
||
176 | * |
||
177 | * @param string $field The name of the field to check for validity. |
||
178 | * @return bool Returns true if the field has no errors, false otherwise. |
||
179 | */ |
||
180 | 28 | public function isValidField($field) { |
|
181 | 28 | $result = !isset($this->errors[$field]) || count($this->errors[$field]) === 0; |
|
182 | 28 | return $result; |
|
183 | } |
||
184 | |||
185 | /** |
||
186 | * Get the error message for an error row. |
||
187 | * |
||
188 | * @param array $error The error row. |
||
189 | * @return string Returns a formatted/translated error message. |
||
190 | */ |
||
191 | 47 | private function getErrorMessage(array $error) { |
|
192 | 47 | if (isset($error['messageCode'])) { |
|
193 | 41 | $messageCode = $error['messageCode']; |
|
194 | 47 | } elseif (isset($error['message'])) { |
|
195 | return $error['message']; |
||
196 | } else { |
||
197 | 7 | $messageCode = $error['code']; |
|
198 | } |
||
199 | |||
200 | // Massage the field name for better formatting. |
||
201 | 47 | if (!$this->getTranslateFieldNames()) { |
|
202 | 47 | $field = (!empty($error['path']) ? ($error['path'][0] !== '[' ?: 'item').$error['path'].'.' : '').$error['field']; |
|
203 | 47 | $field = $field ?: (isset($error['index']) ? 'item' : 'value'); |
|
204 | 47 | if (isset($error['index'])) { |
|
205 | 3 | $field .= '['.$error['index'].']'; |
|
206 | 3 | } |
|
207 | 47 | $error['field'] = $field; |
|
208 | 47 | } elseif (isset($error['index'])) { |
|
209 | if (empty($error['field'])) { |
||
210 | $error['field'] = '@'.$this->formatMessage('item {index}', $error); |
||
211 | } else { |
||
212 | $error['field'] = '@'.$this->formatMessage('{field} at position {index}', $error); |
||
213 | } |
||
214 | } elseif (empty($error['field'])) { |
||
215 | $error['field'] = 'value'; |
||
216 | } |
||
217 | |||
218 | 47 | $msg = $this->formatMessage($messageCode, $error); |
|
219 | 47 | return $msg; |
|
220 | } |
||
221 | |||
222 | /** |
||
223 | * Expand and translate a message format against an array of values. |
||
224 | * |
||
225 | * @param string $format The message format. |
||
226 | * @param array $context The context arguments to apply to the message. |
||
227 | * @return string Returns a formatted string. |
||
228 | */ |
||
229 | 47 | private function formatMessage($format, $context = []) { |
|
230 | 47 | $format = $this->translate($format); |
|
231 | |||
232 | 47 | $msg = preg_replace_callback('`({[^{}]+})`', function ($m) use ($context) { |
|
233 | 44 | $args = array_filter(array_map('trim', explode(',', trim($m[1], '{}')))); |
|
1 ignored issue
–
show
|
|||
234 | 44 | $field = array_shift($args); |
|
235 | 44 | return $this->formatField(isset($context[$field]) ? $context[$field] : null, $args); |
|
236 | 47 | }, $format); |
|
237 | 47 | return $msg; |
|
238 | } |
||
239 | |||
240 | /** |
||
241 | * Translate an argument being placed in an error message. |
||
242 | * |
||
243 | * @param mixed $value The argument to translate. |
||
244 | * @param array $args Formatting arguments. |
||
245 | * @return string Returns the translated string. |
||
246 | */ |
||
247 | 44 | private function formatField($value, array $args = []) { |
|
248 | 44 | if (is_string($value)) { |
|
249 | 43 | $r = $this->translate($value); |
|
250 | 44 | } elseif (is_numeric($value)) { |
|
251 | 2 | $r = $value; |
|
252 | 5 | } elseif (is_array($value)) { |
|
253 | 3 | $argArray = array_map([$this, 'formatField'], $value); |
|
254 | 3 | $r = implode(', ', $argArray); |
|
255 | 3 | } elseif ($value instanceof \DateTimeInterface) { |
|
256 | $r = $value->format('c'); |
||
257 | } else { |
||
258 | $r = $value; |
||
259 | } |
||
260 | |||
261 | 44 | $format = array_shift($args); |
|
262 | switch ($format) { |
||
263 | 44 | case 'plural': |
|
264 | 3 | $singular = array_shift($args); |
|
265 | 3 | $plural = array_shift($args) ?: $singular.'s'; |
|
266 | 3 | $count = is_array($value) ? count($value) : $value; |
|
267 | 3 | $r = $count == 1 ? $singular : $plural; |
|
268 | 3 | break; |
|
269 | } |
||
270 | |||
271 | 44 | return (string)$r; |
|
272 | } |
||
273 | |||
274 | /** |
||
275 | * Translate a string. |
||
276 | * |
||
277 | * This method doesn't do any translation itself, but is meant for subclasses wanting to add translation ability to |
||
278 | * this class. |
||
279 | * |
||
280 | * @param string $str The string to translate. |
||
281 | * @return string Returns the translated string. |
||
282 | */ |
||
283 | 47 | protected function translate($str) { |
|
284 | 47 | if (substr($str, 0, 1) === '@') { |
|
285 | // This is a literal string that bypasses translation. |
||
286 | return substr($str, 1); |
||
287 | } else { |
||
288 | 47 | return $str; |
|
289 | } |
||
290 | } |
||
291 | |||
292 | /** |
||
293 | * Merge another validation object with this one. |
||
294 | * |
||
295 | * @param Validation $validation The validation object to merge. |
||
296 | * @param string $name The path to merge to. Use this parameter when the validation object is meant to be a subset of this one. |
||
297 | * @return $this |
||
298 | */ |
||
299 | 1 | public function merge(Validation $validation, $name = '') { |
|
300 | 1 | $paths = $validation->errors; |
|
301 | |||
302 | 1 | foreach ($paths as $path => $errors) { |
|
303 | 1 | foreach ($errors as $error) { |
|
304 | 1 | if (!empty($name)) { |
|
305 | 1 | $fullPath = "{$name}.{$path}"; |
|
306 | 1 | $this->addError($fullPath, $error['code'], $error); |
|
307 | 1 | } |
|
308 | 1 | } |
|
309 | 1 | } |
|
310 | 1 | return $this; |
|
311 | } |
||
312 | |||
313 | /** |
||
314 | * Get the main error message. |
||
315 | * |
||
316 | * If set, this message will be returned as the error message. Otherwise the message will be set from individual |
||
317 | * errors. |
||
318 | * |
||
319 | * @return string Returns the main message. |
||
320 | */ |
||
321 | public function getMainMessage() { |
||
322 | return $this->mainMessage; |
||
323 | } |
||
324 | |||
325 | /** |
||
326 | * Set the main error message. |
||
327 | * |
||
328 | * @param string $message The new message. |
||
329 | * @return $this |
||
330 | */ |
||
331 | 1 | public function setMainMessage($message) { |
|
335 | |||
336 | /** |
||
337 | * Get the main status. |
||
338 | * |
||
339 | * @return int Returns an HTTP response code or zero to indicate it should be calculated. |
||
340 | */ |
||
341 | public function getMainStatus() { |
||
342 | return $this->mainStatus; |
||
343 | } |
||
344 | |||
345 | /** |
||
346 | * Set the main status. |
||
347 | * |
||
348 | * @param int $status An HTTP response code or zero. |
||
349 | * @return $this |
||
350 | */ |
||
351 | 1 | public function setMainStatus($status) { |
|
355 | |||
356 | /** |
||
357 | * Whether or not fields should be translated. |
||
358 | * |
||
359 | * @return bool Returns **true** if field names are translated or **false** otherwise. |
||
360 | */ |
||
361 | 47 | public function getTranslateFieldNames() { |
|
364 | |||
365 | /** |
||
366 | * Set whether or not fields should be translated. |
||
367 | * |
||
368 | * @param bool $translate Whether or not fields should be translated. |
||
369 | * @return $this |
||
370 | */ |
||
371 | public function setTranslateFieldNames($translate) { |
||
372 | $this->translateFieldNames = $translate; |
||
373 | return $this; |
||
374 | } |
||
375 | } |
||
376 |
This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.
To visualize
will produce issues in the first and second line, while this second example
will produce no issues.