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 |
||
15 | class Action |
||
16 | { |
||
17 | /** |
||
18 | * The list of changes to apply to the Page |
||
19 | * @var array[Change] |
||
20 | */ |
||
21 | private $changes; |
||
22 | |||
23 | /** |
||
24 | * The Page ID to apply changes to |
||
25 | * @var integer |
||
26 | */ |
||
27 | private $pageId; |
||
28 | |||
29 | /** |
||
30 | * The share link for the provided Variation and Page combination |
||
31 | * @var string |
||
32 | */ |
||
33 | private $shareLink; |
||
34 | |||
35 | /** |
||
36 | * Constructor. |
||
37 | */ |
||
38 | 7 | public function __construct($options = array()) |
|
39 | { |
||
40 | 7 | foreach ($options as $name=>$value) { |
|
41 | switch ($name) { |
||
42 | 6 | View Code Duplication | case 'changes': { |
43 | 6 | $changes = array(); |
|
44 | 6 | foreach ($value as $changeInfo) { |
|
45 | 6 | $changes[] = new Change($changeInfo); |
|
46 | 6 | } |
|
47 | 6 | $this->setChanges($changes); break; |
|
48 | } |
||
49 | 6 | case 'page_id': $this->setPageId($value); break; |
|
50 | case 'share_link': $this->setShareLink($value); break; |
||
51 | default: |
||
52 | throw new Exception('Unknown option found in the Action entity: ' . $name); |
||
53 | } |
||
54 | 7 | } |
|
55 | 7 | } |
|
56 | |||
57 | /** |
||
58 | * Returns this object as array. |
||
59 | */ |
||
60 | 3 | public function toArray() |
|
61 | { |
||
62 | $options = array( |
||
63 | 3 | 'changes' => array(), |
|
64 | 3 | 'page_id' => $this->getPageId(), |
|
65 | 3 | 'share_link' => $this->getShareLink(), |
|
66 | 3 | ); |
|
67 | |||
68 | 3 | foreach ($this->getChanges() as $change) { |
|
69 | 3 | $options['changes'][] = $change->toArray(); |
|
70 | 3 | } |
|
71 | |||
72 | // Remove options with empty values |
||
73 | 3 | $cleanedOptions = array(); |
|
74 | 3 | foreach ($options as $name=>$value) { |
|
75 | 3 | if ($value!==null) |
|
76 | 3 | $cleanedOptions[$name] = $value; |
|
77 | 3 | } |
|
78 | |||
79 | 3 | return $cleanedOptions; |
|
80 | } |
||
81 | |||
82 | 3 | public function getChanges() |
|
86 | |||
87 | 7 | public function setChanges($changes) |
|
91 | |||
92 | 3 | public function getPageId() |
|
96 | |||
97 | 7 | public function setPageId($pageId) |
|
101 | |||
102 | 3 | public function getShareLink() |
|
106 | |||
107 | public function setShareLink($shareLink) |
||
111 | } |
||
112 | |||
113 | |||
122 |
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.