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 |
||
| 10 | class EventManager implements EventManagerInterface |
||
| 11 | { |
||
| 12 | private $listenersHeap = []; |
||
| 13 | |||
| 14 | /** |
||
| 15 | * Attaches a listener to an event |
||
| 16 | * |
||
| 17 | * @param string $event the event to attach too |
||
| 18 | * @param callable $callback a callable function |
||
| 19 | * @param int $priority the priority at which the $callback executed |
||
| 20 | * @return bool true on success false on failure |
||
| 21 | */ |
||
| 22 | public function attach($event, $callback, $priority = 0) |
||
| 38 | |||
| 39 | /** |
||
| 40 | * Detaches a listener from an event |
||
| 41 | * |
||
| 42 | * @param string $event the event to attach too |
||
| 43 | * @param callable $callback a callable function |
||
| 44 | * @return bool true on success false on failure |
||
| 45 | */ |
||
| 46 | public function detach($event, $callback) |
||
| 58 | |||
| 59 | /** |
||
| 60 | * Clear all listeners for a given event |
||
| 61 | * |
||
| 62 | * @param string $event |
||
| 63 | * @return bool true on success false on failure |
||
| 64 | */ |
||
| 65 | View Code Duplication | public function clearListeners($event) |
|
| 76 | |||
| 77 | /** |
||
| 78 | * Trigger an event |
||
| 79 | * |
||
| 80 | * Can accept an EventInterface or will create one if not passed |
||
| 81 | * |
||
| 82 | * @param string|EventInterface $event |
||
| 83 | * @param object|string $target |
||
| 84 | * @param array|object $argv - arguments for listener callback |
||
| 85 | * @return mixed |
||
| 86 | */ |
||
| 87 | public function trigger($event, $target = null, $argv = []) |
||
| 116 | |||
| 117 | /** |
||
| 118 | * Custom method for check event listeners |
||
| 119 | * |
||
| 120 | * @param string $event |
||
| 121 | * @return bool true on success false on failure |
||
| 122 | */ |
||
| 123 | View Code Duplication | public function isExistListeners($event) |
|
| 133 | } |
||
| 134 |
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.