Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like HasMany 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 HasMany, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
62 | class HasMany extends Field |
||
63 | { |
||
64 | /** |
||
65 | * Relation name. |
||
66 | * |
||
67 | * @var string |
||
68 | */ |
||
69 | protected $relationName = ''; |
||
70 | |||
71 | /** |
||
72 | * Form builder. |
||
73 | * |
||
74 | * @var \Closure |
||
75 | */ |
||
76 | protected $builder = null; |
||
77 | |||
78 | /** |
||
79 | * Form data. |
||
80 | * |
||
81 | * @var array |
||
82 | */ |
||
83 | protected $value = []; |
||
84 | |||
85 | /** |
||
86 | * View Mode. |
||
87 | * |
||
88 | * Supports `default` and `tab` currently. |
||
89 | * |
||
90 | * @var string |
||
91 | */ |
||
92 | protected $viewMode = 'default'; |
||
93 | |||
94 | /** |
||
95 | * Available views for HasMany field. |
||
96 | * |
||
97 | * @var array |
||
98 | */ |
||
99 | protected $views = [ |
||
100 | 'default' => 'admin::form.hasmany', |
||
101 | 'tab' => 'admin::form.hasmanytab', |
||
102 | 'table' => 'admin::form.hasmanytable', |
||
103 | ]; |
||
104 | |||
105 | /** |
||
106 | * Options for template. |
||
107 | * |
||
108 | * @var array |
||
109 | */ |
||
110 | protected $options = [ |
||
111 | 'allowCreate' => true, |
||
112 | 'allowDelete' => true, |
||
113 | ]; |
||
114 | |||
115 | /** |
||
116 | * Create a new HasMany field instance. |
||
117 | * |
||
118 | * @param $relationName |
||
119 | * @param array $arguments |
||
120 | */ |
||
121 | View Code Duplication | public function __construct($relationName, $arguments = []) |
|
122 | { |
||
123 | $this->relationName = $relationName; |
||
124 | |||
125 | $this->column = $relationName; |
||
126 | |||
127 | if (count($arguments) == 1) { |
||
128 | $this->label = $this->formatLabel(); |
||
129 | $this->builder = $arguments[0]; |
||
130 | } |
||
131 | |||
132 | if (count($arguments) == 2) { |
||
133 | list($this->label, $this->builder) = $arguments; |
||
134 | } |
||
135 | } |
||
136 | |||
137 | /** |
||
138 | * Get validator for this field. |
||
139 | * |
||
140 | * @param array $input |
||
141 | * |
||
142 | * @return bool|Validator |
||
143 | */ |
||
144 | public function getValidator(array $input) |
||
145 | { |
||
146 | if (!array_key_exists($this->column, $input)) { |
||
147 | return false; |
||
148 | } |
||
149 | |||
150 | $input = array_only($input, $this->column); |
||
151 | $form = $this->buildNestedForm($this->column, $this->builder); |
||
152 | $rel = $this->relationName; |
||
153 | $rules = $attributes = $messages = $newInputs = []; |
||
154 | // remove all inputs & keys marked as removed |
||
155 | $availInput = array_filter(array_map(function ($v) { |
||
156 | return $v[NestedForm::REMOVE_FLAG_NAME] ? null : $v; |
||
157 | }, $input[$rel])); |
||
158 | $keys = array_keys($availInput); |
||
159 | /* @var Field $field */ |
||
160 | foreach ($form->fields() as $field) { |
||
161 | if ($field instanceof Field\HasMany) { |
||
162 | throw new \Exception('nested hasMany field found.'); |
||
163 | } |
||
164 | if (!($field instanceof Field\Embeds) && !($fieldRules = $field->getRules())) { |
||
165 | continue; |
||
166 | } |
||
167 | $column = $field->column(); |
||
168 | $columns = is_array($column) ? $column : [$column]; |
||
169 | View Code Duplication | if ( |
|
170 | $field instanceof Field\MultipleSelect |
||
171 | || $field instanceof Field\Listbox |
||
172 | || $field instanceof Field\Checkbox |
||
173 | || $field instanceof Field\Tags |
||
174 | || $field instanceof Field\MultipleImage |
||
175 | || $field instanceof Field\MultipleFile |
||
176 | ) { |
||
177 | foreach ($keys as $key) { |
||
178 | $availInput[$key][$column] = array_filter($availInput[$key][$column], 'strlen') ?: null; |
||
179 | } |
||
180 | } |
||
181 | |||
182 | $newColumn = call_user_func_array('array_merge', array_map(function ($u) use ($columns, $rel) { |
||
183 | return array_map(function ($k, $v) use ($u, $rel) { |
||
184 | //Fix ResetInput Function! A Headache Implementation! |
||
185 | return $k ? "{$rel}.{$u}.{$v}:{$k}" : "{$rel}.{$u}.{$v}"; |
||
186 | }, array_keys($columns), array_values($columns)); |
||
187 | }, $keys)); |
||
188 | |||
189 | if ($field instanceof Field\Embeds) { |
||
190 | View Code Duplication | $newRules = array_map(function ($v) use ($availInput, $field) { |
|
191 | list($r, $k, $c) = explode('.', $v); |
||
192 | $v = "{$r}.{$k}"; |
||
193 | $embed = $field->getValidationRules([$field->column() => $availInput[$k][$c]]); |
||
194 | |||
195 | return $embed ? array_key_attach_str($embed, $v) : null; |
||
196 | }, $newColumn); |
||
197 | $rules = array_clean_merge($rules, array_filter($newRules)); |
||
198 | |||
199 | View Code Duplication | $newAttributes = array_map(function ($v) use ($availInput, $field) { |
|
200 | list($r, $k, $c) = explode('.', $v); |
||
201 | $v = "{$r}.{$k}"; |
||
202 | $embed = $field->getValidationAttributes([$field->column() => $availInput[$k][$c]]); |
||
203 | |||
204 | return $embed ? array_key_attach_str($embed, $v) : null; |
||
205 | }, $newColumn); |
||
206 | $attributes = array_clean_merge($attributes, array_filter($newAttributes)); |
||
207 | |||
208 | View Code Duplication | $newInput = array_map(function ($v) use ($availInput, $field) { |
|
209 | list($r, $k, $c) = explode('.', $v); |
||
210 | $v = "{$r}.{$k}"; |
||
211 | $embed = $field->getValidationInput([$field->column() => $availInput[$k][$c]]); |
||
212 | |||
213 | return $embed ? array_key_attach_str($embed, $v) : [null => 'null']; |
||
214 | }, $newColumn); |
||
215 | $newInputs = array_clean_merge($newInputs, array_filter($newInput, 'strlen', ARRAY_FILTER_USE_KEY)); |
||
216 | |||
217 | View Code Duplication | $newMessages = array_map(function ($v) use ($availInput, $field) { |
|
218 | list($r, $k, $c) = explode('.', $v); |
||
219 | $v = "{$r}.{$k}"; |
||
220 | $embed = $field->getValidationMessages([$field->column() => $availInput[$k][$c]]); |
||
221 | |||
222 | return $embed ? array_key_attach_str($embed, $v) : null; |
||
223 | }, $newColumn); |
||
224 | $messages = array_clean_merge($messages, array_filter($newMessages)); |
||
225 | } else { |
||
226 | $fieldRules = is_array($fieldRules) ? implode('|', $fieldRules) : $fieldRules; |
||
227 | View Code Duplication | $newRules = array_map(function ($v) use ($fieldRules, $availInput) { |
|
228 | list($r, $k, $c) = explode('.', $v); |
||
229 | //Fix ResetInput Function! A Headache Implementation! |
||
230 | $col = explode(':', $c)[0]; |
||
231 | if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) { |
||
232 | return array_key_attach_str(preg_replace('/.+/', $fieldRules, $availInput[$k][$col]), $v, ':'); |
||
233 | } |
||
234 | |||
235 | return [$v => $fieldRules]; |
||
236 | }, $newColumn); |
||
237 | $rules = array_clean_merge($rules, $newRules); |
||
238 | |||
239 | View Code Duplication | $newInput = array_map(function ($v) use ($availInput) { |
|
240 | list($r, $k, $c) = explode('.', $v); |
||
241 | //Fix ResetInput Function! A Headache Implementation! |
||
242 | $col = explode(':', $c)[0]; |
||
243 | if (!array_key_exists($col, $availInput[$k])) { |
||
244 | return [$v => null]; |
||
245 | } |
||
246 | |||
247 | if (is_array($availInput[$k][$col])) { |
||
248 | return array_key_attach_str($availInput[$k][$col], $v, ':'); |
||
249 | } |
||
250 | |||
251 | return [$v => $availInput[$k][$col]]; |
||
252 | }, $newColumn); |
||
253 | $newInputs = array_clean_merge($newInputs, $newInput); |
||
254 | |||
255 | View Code Duplication | $newAttributes = array_map(function ($v) use ($field, $availInput) { |
|
256 | list($r, $k, $c) = explode('.', $v); |
||
257 | //Fix ResetInput Function! A Headache Implementation! |
||
258 | $col = explode(':', $c)[0]; |
||
259 | if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) { |
||
260 | return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field) { |
||
261 | $w = $field->label(); |
||
262 | //Fix ResetInput Function! A Headache Implementation! |
||
263 | $w .= is_array($field->column()) ? '[' . explode(':', explode('.', $v)[2])[0] . ']' : ''; |
||
264 | |||
265 | return ["{$v}:{$u}" => $w]; |
||
266 | }, array_keys($availInput[$k][$col]))); |
||
267 | } |
||
268 | |||
269 | $w = $field->label(); |
||
270 | //Fix ResetInput Function! A Headache Implementation! |
||
271 | $w .= is_array($field->column()) ? '[' . explode(':', explode('.', $v)[2])[0] . ']' : ''; |
||
272 | |||
273 | return [$v => $w]; |
||
274 | }, $newColumn); |
||
275 | $attributes = array_clean_merge($attributes, $newAttributes); |
||
276 | } |
||
277 | |||
278 | View Code Duplication | if ($field->validationMessages) { |
|
279 | $newMessages = array_map(function ($v) use ($field, $availInput) { |
||
280 | list($r, $k, $c) = explode('.', $v); |
||
281 | //Fix ResetInput Function! A Headache Implementation! |
||
282 | $col = explode(':', $c)[0]; |
||
283 | if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) { |
||
284 | return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field) { |
||
285 | return array_key_attach_str($field->validationMessages, "{$v}:{$u}"); |
||
286 | }, array_keys($availInput[$k][$col]))); |
||
287 | } |
||
288 | |||
289 | return array_key_attach_str($field->validationMessages, $v); |
||
290 | }, $newColumn); |
||
291 | $messages = array_clean_merge($messages, $newMessages); |
||
292 | } |
||
293 | } |
||
294 | |||
295 | $rules = array_filter($rules, 'strlen'); |
||
296 | if (empty($rules)) { |
||
297 | return false; |
||
298 | } |
||
299 | |||
300 | $input = array_key_clean_undot(array_filter($newInputs, 'strlen', ARRAY_FILTER_USE_KEY)); |
||
301 | $rules = array_key_clean($rules); |
||
302 | $attributes = array_key_clean($attributes); |
||
303 | $messages = array_key_clean($messages); |
||
304 | |||
305 | if (empty($input)) { |
||
306 | $input = [$rel => $availInput]; |
||
307 | } |
||
308 | |||
309 | return Validator::make($input, $rules, $messages, $attributes); |
||
310 | } |
||
311 | |||
312 | |||
313 | /** |
||
314 | * Prepare input data for insert or update. |
||
315 | * |
||
316 | * @param array $input |
||
317 | * |
||
318 | * @return array |
||
319 | */ |
||
320 | public function prepare($input) |
||
321 | { |
||
322 | $form = $this->buildNestedForm($this->column, $this->builder); |
||
323 | |||
324 | return $form->setOriginal($this->original, $this->getKeyName())->prepare($input); |
||
325 | } |
||
326 | |||
327 | /** |
||
328 | * Build a Nested form. |
||
329 | * |
||
330 | * @param string $column |
||
331 | * @param \Closure $builder |
||
332 | * @param null $key |
||
333 | * |
||
334 | * @return NestedForm |
||
335 | */ |
||
336 | protected function buildNestedForm($column, \Closure $builder, $key = null) |
||
337 | { |
||
338 | $form = new Form\NestedForm($column, $key); |
||
339 | |||
340 | $form->setForm($this->form); |
||
341 | |||
342 | call_user_func($builder, $form); |
||
343 | |||
344 | $form->hidden($this->getKeyName()); |
||
345 | |||
346 | $form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS); |
||
347 | |||
348 | return $form; |
||
349 | } |
||
350 | |||
351 | /** |
||
352 | * Get the HasMany relation key name. |
||
353 | * |
||
354 | * @return string |
||
355 | */ |
||
356 | protected function getKeyName() |
||
357 | { |
||
358 | if (is_null($this->form)) { |
||
359 | return; |
||
360 | } |
||
361 | |||
362 | return $this->form->model()->{$this->relationName}()->getRelated()->getKeyName(); |
||
363 | } |
||
364 | |||
365 | /** |
||
366 | * Set view mode. |
||
367 | * |
||
368 | * @param string $mode currently support `tab` mode. |
||
369 | * |
||
370 | * @return $this |
||
371 | * |
||
372 | * @author Edwin Hui |
||
373 | */ |
||
374 | public function mode($mode) |
||
375 | { |
||
376 | $this->viewMode = $mode; |
||
377 | |||
378 | return $this; |
||
379 | } |
||
380 | |||
381 | /** |
||
382 | * Use tab mode to showing hasmany field. |
||
383 | * |
||
384 | * @return HasMany |
||
385 | */ |
||
386 | public function useTab() |
||
387 | { |
||
388 | return $this->mode('tab'); |
||
389 | } |
||
390 | |||
391 | /** |
||
392 | * Use table mode to showing hasmany field. |
||
393 | * |
||
394 | * @return HasMany |
||
395 | */ |
||
396 | public function useTable() |
||
397 | { |
||
398 | return $this->mode('table'); |
||
399 | } |
||
400 | |||
401 | /** |
||
402 | * Build Nested form for related data. |
||
403 | * |
||
404 | * @throws \Exception |
||
405 | * |
||
406 | * @return array |
||
407 | */ |
||
408 | protected function buildRelatedForms() |
||
409 | { |
||
410 | if (is_null($this->form)) { |
||
411 | return []; |
||
412 | } |
||
413 | |||
414 | $model = $this->form->model(); |
||
415 | |||
416 | $relation = call_user_func([$model, $this->relationName]); |
||
417 | |||
418 | if (!$relation instanceof Relation && !$relation instanceof MorphMany) { |
||
419 | throw new \Exception('hasMany field must be a HasMany or MorphMany relation.'); |
||
420 | } |
||
421 | |||
422 | $forms = []; |
||
423 | |||
424 | /* |
||
425 | * If redirect from `exception` or `validation error` page. |
||
426 | * |
||
427 | * Then get form data from session flash. |
||
428 | * |
||
429 | * Else get data from database. |
||
430 | */ |
||
431 | if ($values = old($this->column)) { |
||
432 | foreach ($values as $key => $data) { |
||
433 | if ($data[NestedForm::REMOVE_FLAG_NAME] == 1) { |
||
434 | continue; |
||
435 | } |
||
436 | |||
437 | $forms[$key] = $this->buildNestedForm($this->column, $this->builder, $key) |
||
438 | ->fill($data); |
||
439 | } |
||
440 | } else { |
||
441 | foreach ($this->value as $data) { |
||
442 | $key = array_get($data, $relation->getRelated()->getKeyName()); |
||
443 | |||
444 | $forms[$key] = $this->buildNestedForm($this->column, $this->builder, $key) |
||
445 | ->fill($data); |
||
446 | } |
||
447 | } |
||
448 | |||
449 | return $forms; |
||
450 | } |
||
451 | |||
452 | /** |
||
453 | * Setup script for this field in different view mode. |
||
454 | * |
||
455 | * @param string $script |
||
456 | * |
||
457 | * @return void |
||
458 | */ |
||
459 | protected function setupScript($script) |
||
465 | |||
466 | /** |
||
467 | * Setup default template script. |
||
468 | * |
||
469 | * @param string $templateScript |
||
470 | * |
||
471 | * @return void |
||
472 | */ |
||
473 | View Code Duplication | protected function setupScriptForDefaultView($templateScript) |
|
507 | |||
508 | /** |
||
509 | * Setup tab template script. |
||
510 | * |
||
511 | * @param string $templateScript |
||
512 | * |
||
513 | * @return void |
||
514 | */ |
||
515 | View Code Duplication | protected function setupScriptForTabView($templateScript) |
|
562 | |||
563 | /** |
||
564 | * Setup default template script. |
||
565 | * |
||
566 | * @param string $templateScript |
||
567 | * |
||
568 | * @return void |
||
569 | */ |
||
570 | View Code Duplication | protected function setupScriptForTableView($templateScript) |
|
571 | { |
||
604 | |||
605 | /** |
||
606 | * Disable create button. |
||
607 | * |
||
608 | * @return $this |
||
609 | */ |
||
610 | public function disableCreate() |
||
616 | |||
617 | /** |
||
618 | * Disable delete button. |
||
619 | * |
||
620 | * @return $this |
||
621 | */ |
||
622 | public function disableDelete() |
||
628 | |||
629 | /** |
||
630 | * Render the `HasMany` field. |
||
631 | * |
||
632 | * @throws \Exception |
||
633 | * |
||
634 | * @return \Illuminate\View\View |
||
635 | */ |
||
636 | public function render() |
||
657 | |||
658 | /** |
||
659 | * Render the `HasMany` field for table style. |
||
660 | * |
||
661 | * @throws \Exception |
||
662 | * |
||
663 | * @return mixed |
||
664 | */ |
||
665 | protected function renderTable() |
||
715 | } |
||
716 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.