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 |
||
5 | class AtomicTempFileObject extends \SplFileObject |
||
6 | { |
||
7 | const DISCARD = 1; |
||
8 | const PERSIST = 2; |
||
9 | const PERSIST_UNCHANGED = 3; |
||
10 | |||
11 | protected $destinationRealPath; |
||
12 | protected $persist = 0; |
||
13 | protected $onPersistCallback; |
||
14 | protected $onDiscardCallback; |
||
15 | protected $onCompareCallback; |
||
16 | |||
17 | /** |
||
18 | * Constructor. |
||
19 | */ |
||
20 | 21 | public function __construct(string $filename, $mode = 0755) |
|
42 | |||
43 | /** |
||
44 | * Get the destination real path. |
||
45 | * |
||
46 | * @return string |
||
47 | * The real path of the destination. |
||
48 | */ |
||
49 | 15 | public function getDestinationRealPath(): string |
|
53 | |||
54 | /** |
||
55 | * Move temp file into the destination upon object desctruction. |
||
56 | */ |
||
57 | 20 | public function persistOnClose($persist = self::PERSIST): AtomicTempFileObject |
|
62 | |||
63 | 1 | public function onPersist(callable $callback) |
|
67 | |||
68 | 1 | public function onDiscard(callable $callback) |
|
72 | |||
73 | 21 | public function onCompare(callable $callback) |
|
77 | |||
78 | 12 | private function doPersist() |
|
97 | |||
98 | 12 | private function doDiscard() |
|
116 | |||
117 | 12 | private function doCompare() |
|
121 | |||
122 | /** |
||
123 | * Move temp file into the destination if applicable. |
||
124 | */ |
||
125 | 21 | public function __destruct() |
|
142 | |||
143 | /** |
||
144 | * Easy access iterator apply for processing an entire file. |
||
145 | * |
||
146 | * @param \Iterator $input [description] |
||
147 | * @param callable $callback [description] |
||
148 | */ |
||
149 | 1 | View Code Duplication | public function process(\Iterator $input, callable $callback) |
163 | |||
164 | /** |
||
165 | * Atomic file_put_contents(). |
||
166 | * |
||
167 | * @see file_put_contents() |
||
168 | */ |
||
169 | 1 | public static function file_put_contents($filename, $data, $flags = 0) |
|
182 | |||
183 | /** |
||
184 | * File comparison |
||
185 | * |
||
186 | * @return bool |
||
187 | * True if the contents of this file matches the contents of $filename. |
||
188 | */ |
||
189 | 12 | private static function compare(AtomicTempFileObject $tempFile): bool |
|
219 | } |
||
220 |
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.