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 |
||
11 | class Node extends \stdClass |
||
12 | { |
||
13 | /** |
||
14 | * The processed data |
||
15 | * @var mixed |
||
16 | */ |
||
17 | protected $i_result; |
||
18 | |||
19 | /** |
||
20 | * Class constructor |
||
21 | * |
||
22 | * @param \stdClass $data |
||
23 | */ |
||
24 | public function __construct(\stdClass $data) |
||
36 | |||
37 | |||
38 | /** |
||
39 | * Replace nodes with their results |
||
40 | * |
||
41 | * @param array|object $target |
||
42 | */ |
||
43 | View Code Duplication | protected function applyNodeResults(&$target) |
|
44 | { |
||
45 | if (!is_array($target) && !is_object($target)) { |
||
46 | return; |
||
47 | } |
||
48 | |||
49 | foreach ($target as &$value) { |
||
50 | if ($value instanceof self) { |
||
51 | $value = $value->getResult(); |
||
52 | } |
||
53 | |||
54 | $this->applyNodeResults($value); |
||
55 | } |
||
56 | } |
||
57 | |||
58 | /** |
||
59 | * Get the processed result |
||
60 | * |
||
61 | * @return mixed |
||
62 | */ |
||
63 | public function getResult() |
||
64 | { |
||
65 | if ($this->i_result instanceof PromiseInterface) { |
||
66 | $result = $this->i_result->wait(); |
||
67 | } else { |
||
68 | $result = $this->i_result; |
||
69 | } |
||
70 | |||
71 | $this->applyNodeResults($result); |
||
72 | return $result; |
||
73 | } |
||
74 | |||
75 | /** |
||
76 | * Set the result after processing |
||
77 | * |
||
78 | * @param mixed $result |
||
79 | */ |
||
80 | public function setResult($result) |
||
84 | |||
85 | |||
86 | /** |
||
87 | * Test if the node has an instruction for a processor |
||
88 | * |
||
89 | * @param Processor $processor |
||
90 | * @return boolean |
||
91 | */ |
||
92 | public function hasInstruction(Processor $processor) |
||
97 | |||
98 | /** |
||
99 | * Get an instruction for a processor |
||
100 | * |
||
101 | * @param Processor $processor |
||
102 | * @return mixed |
||
103 | */ |
||
104 | public function getInstruction(Processor $processor) |
||
120 | |||
121 | /** |
||
122 | * Apply processing to this node |
||
123 | * |
||
124 | * @param Processor $processor |
||
125 | */ |
||
126 | public function apply(Processor $processor) |
||
140 | } |
||
141 |