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 |
||
17 | class Semaphore implements LockInterface |
||
18 | { |
||
19 | /** |
||
20 | * @var |
||
21 | */ |
||
22 | private $lock_id; |
||
23 | /** |
||
24 | * @var bool |
||
25 | */ |
||
26 | private $locked = false; |
||
27 | |||
28 | /** |
||
29 | * init a lock |
||
30 | * |
||
31 | * @param $key |
||
32 | * @param $count |
||
33 | * @throws \RuntimeException |
||
34 | */ |
||
35 | 9 | private function __construct($key, $count = 1) |
|
36 | { |
||
37 | 9 | if (($this->lock_id = sem_get($this->_stringToSemKey($key), $count)) === false) { |
|
38 | throw new \RuntimeException("Cannot create semaphore for key: {$key}"); |
||
39 | } |
||
40 | 9 | } |
|
41 | |||
42 | /** |
||
43 | * Semaphore requires a numeric value as the key |
||
44 | * |
||
45 | * @param $identifier |
||
46 | * @return int |
||
47 | */ |
||
48 | 9 | protected function _stringToSemKey($identifier) |
|
57 | |||
58 | /** |
||
59 | * create a lock instance |
||
60 | * |
||
61 | * @param $key |
||
62 | * @return Semaphore |
||
63 | */ |
||
64 | 9 | public static function create($key) |
|
68 | |||
69 | /** |
||
70 | * release lock |
||
71 | * |
||
72 | * @throws \RuntimeException |
||
73 | */ |
||
74 | 9 | public function __destruct() |
|
80 | |||
81 | /** |
||
82 | * is locked |
||
83 | * |
||
84 | * @return bool |
||
85 | */ |
||
86 | 9 | public function isLocked() |
|
90 | |||
91 | /** |
||
92 | * release lock |
||
93 | * |
||
94 | * @return bool |
||
95 | * @throws \RuntimeException |
||
96 | */ |
||
97 | 9 | View Code Duplication | public function release() |
|
|||
98 | { |
||
99 | 9 | if (!$this->locked) { |
|
100 | 3 | throw new \RuntimeException("release a non lock"); |
|
101 | } |
||
102 | |||
103 | 6 | if (!sem_release($this->lock_id)) { |
|
104 | return false; |
||
105 | } |
||
106 | 6 | $this->locked = false; |
|
107 | |||
108 | 6 | return true; |
|
109 | } |
||
110 | |||
111 | /** |
||
112 | * get a lock |
||
113 | * |
||
114 | * @param bool $blocking |
||
115 | * @return bool |
||
116 | */ |
||
117 | 6 | public function acquire($blocking = true) |
|
142 | |||
143 | /** |
||
144 | * remove the semaphore resource |
||
145 | * |
||
146 | * @return bool |
||
147 | */ |
||
148 | View Code Duplication | public function remove() |
|
163 | } |
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.