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 |
||
43 | class Events |
||
44 | { |
||
45 | /** |
||
46 | * Holds all the events and their callbacks. |
||
47 | * @var array |
||
48 | */ |
||
49 | protected $events = []; |
||
50 | |||
51 | /** |
||
52 | * True while an event is fired. |
||
53 | * @var string|bool |
||
54 | */ |
||
55 | protected $inProgress = false; |
||
56 | |||
57 | /** |
||
58 | * Custom sort for priority. |
||
59 | * |
||
60 | * @param array $a |
||
61 | * @param array $b |
||
62 | * |
||
63 | * @return int |
||
64 | */ |
||
65 | public static function prioritySort($a, $b) |
||
73 | |||
74 | /** |
||
75 | * Include all the events files that may register and/or hook to events. |
||
76 | */ |
||
77 | public function __construct() |
||
91 | |||
92 | /** |
||
93 | * Register a new event. |
||
94 | * |
||
95 | * @param string $name |
||
96 | * |
||
97 | * @return bool |
||
98 | */ |
||
99 | public function register($name) |
||
109 | |||
110 | /** |
||
111 | * Check if the event exists by it's name. |
||
112 | * |
||
113 | * @param string $name |
||
114 | * |
||
115 | * @return bool |
||
116 | */ |
||
117 | public function isRegistered($name) |
||
121 | |||
122 | /** |
||
123 | * Remove an event and un-hook everything related to it. |
||
124 | * |
||
125 | * @param string $name |
||
126 | */ |
||
127 | public function unregister($name) |
||
131 | |||
132 | /** |
||
133 | * Hook a callable to an event. |
||
134 | * If the event is not registered, register it. |
||
135 | * |
||
136 | * @param string $name |
||
137 | * @param callable $call |
||
138 | * @param int $priority |
||
139 | * |
||
140 | * @return bool |
||
141 | */ |
||
142 | public function hook($name, $call, $priority = 0) |
||
155 | |||
156 | /** |
||
157 | * Fire an event and call all the hooked callables. |
||
158 | * |
||
159 | * @param string $name |
||
160 | * @param array $params |
||
161 | * |
||
162 | * @return bool |
||
163 | */ |
||
164 | public function fire($name, $params = []) |
||
182 | |||
183 | /** |
||
184 | * Returns the name of the event being fired, false otherwise. |
||
185 | * |
||
186 | * @return string|bool |
||
187 | */ |
||
188 | public function isInProgress() |
||
192 | } |
||
193 |
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.