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 |
||
| 2 | namespace Ackintosh\Snidel; |
||
| 3 | |||
| 4 | class Token |
||
| 5 | { |
||
| 6 | /** @var int */ |
||
| 7 | private $ownerPid; |
||
| 8 | |||
| 9 | /** @var int */ |
||
| 10 | private $concurrency; |
||
| 11 | |||
| 12 | /** @var string */ |
||
| 13 | private $keyPrefix; |
||
| 14 | |||
| 15 | /** @var resource */ |
||
| 16 | private $id; |
||
| 17 | |||
| 18 | /** @const string **/ |
||
| 19 | const TMP_FILE_PREFIX = 'snidel_token_'; |
||
| 20 | |||
| 21 | /** |
||
| 22 | * @param int $ownerPid |
||
| 23 | * @param int $concurrency |
||
| 24 | */ |
||
| 25 | public function __construct($ownerPid, $concurrency) |
||
| 33 | |||
| 34 | /** |
||
| 35 | * wait for the token |
||
| 36 | * |
||
| 37 | * @return bool |
||
| 38 | */ |
||
| 39 | public function accept() |
||
| 45 | |||
| 46 | /** |
||
| 47 | * returns the token |
||
| 48 | */ |
||
| 49 | public function back() |
||
| 54 | |||
| 55 | /** |
||
| 56 | * generate IPC key |
||
| 57 | * |
||
| 58 | * @return int |
||
| 59 | */ |
||
| 60 | View Code Duplication | private function genId() |
|
| 69 | |||
| 70 | private function getKey() |
||
| 74 | |||
| 75 | /** |
||
| 76 | * initialize the queue of token |
||
| 77 | * |
||
| 78 | * @return void |
||
| 79 | */ |
||
| 80 | private function initializeQueue() |
||
| 86 | |||
| 87 | public function __destruct() |
||
| 88 | { |
||
| 89 | if ($this->keyPrefix . getmypid() === $this->getKey()) { |
||
| 90 | unlink('/tmp/' . self::TMP_FILE_PREFIX . sha1($this->getKey())); |
||
| 91 | return msg_remove_queue($this->id); |
||
| 92 | } |
||
| 93 | }// @codeCoverageIgnore |
||
| 95 |
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.