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:
1 | <?php |
||
12 | class UpdateCommentForm extends FormModel |
||
13 | { |
||
14 | /** |
||
15 | * Constructor injects with DI container. |
||
16 | * |
||
17 | * @param Anax\DI\DIInterface $di a service container |
||
18 | */ |
||
19 | 1 | public function __construct(DIInterface $di, $id) |
|
20 | { |
||
21 | 1 | parent::__construct($di); |
|
22 | 1 | $comment = $this->getItemDetails($id); |
|
23 | 1 | $this->form->create( |
|
24 | [ |
||
25 | 1 | "id" => __CLASS__, |
|
26 | 1 | "use_fieldset" => false, |
|
27 | 1 | ], |
|
28 | [ |
||
29 | "id" => [ |
||
30 | 1 | "type" => "hidden", |
|
31 | 1 | "validation" => ["not_empty"], |
|
32 | 1 | "readonly" => true, |
|
33 | 1 | "value" => $comment->id, |
|
34 | 1 | ], |
|
35 | "content" => [ |
||
36 | 1 | "type" => "textarea", |
|
37 | 1 | "label" => "Kommentar", |
|
38 | 1 | "validation" => ["not_empty"], |
|
39 | 1 | "value" => $comment->content, |
|
40 | 1 | ], |
|
41 | |||
42 | "submit" => [ |
||
43 | 1 | "type" => "submit", |
|
44 | 1 | "value" => "Uppdatera kommentar", |
|
45 | 1 | "callback" => [$this, "callbackSubmit"], |
|
46 | "class" => "btn" |
||
47 | 1 | ], |
|
48 | ] |
||
49 | 1 | ); |
|
50 | 1 | } |
|
51 | |||
52 | |||
53 | /** |
||
54 | * Get details on item to load form with. |
||
55 | * |
||
56 | * @param integer $id get details on item with id. |
||
57 | * |
||
58 | * @return Comment true if okey, false if something went wrong. |
||
59 | */ |
||
60 | 1 | public function getItemDetails($id) |
|
61 | { |
||
62 | 1 | $comment = new Comment(); |
|
63 | 1 | $comment->setDb($this->di->get("db")); |
|
64 | 1 | $comment->find("id", $id); |
|
65 | 1 | return $comment; |
|
66 | } |
||
67 | |||
68 | |||
69 | /** |
||
70 | * Callback for submit-button which should return true if it could |
||
71 | * carry out its work and false if something failed. |
||
72 | * |
||
73 | * @return boolean true if okey, false if something went wrong. |
||
74 | */ |
||
75 | View Code Duplication | public function callbackSubmit() |
|
86 | } |
||
87 |
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.