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 |
||
11 | class FilesStorage extends AbstractStorage |
||
12 | { |
||
13 | protected $filesDir; |
||
14 | |||
15 | /** |
||
16 | * @param \CloudControl\Cms\storage\Repository $repository |
||
17 | * @param string $filesDir |
||
18 | */ |
||
19 | public function __construct($repository, $filesDir) |
||
24 | |||
25 | |||
26 | /** |
||
27 | * @return array |
||
28 | */ |
||
29 | public function getFiles() |
||
36 | |||
37 | /** |
||
38 | * @param $postValues |
||
39 | * |
||
40 | * @return \CloudControl\Cms\storage\entities\File |
||
41 | * @throws \Exception |
||
42 | */ |
||
43 | public function addFile($postValues) |
||
66 | |||
67 | /** |
||
68 | * @param $filename |
||
69 | * |
||
70 | * @return \stdClass|null |
||
71 | */ |
||
72 | public function getFileByName($filename) |
||
83 | |||
84 | /** |
||
85 | * @param $filename |
||
86 | * |
||
87 | * @throws \Exception |
||
88 | */ |
||
89 | View Code Duplication | public function deleteFileByName($filename) |
|
|
|||
90 | { |
||
91 | $destinationPath = $this->getDestinationPath(); |
||
92 | $destination = $destinationPath . '/' . $filename; |
||
93 | |||
94 | if (file_exists($destination)) { |
||
95 | $files = $this->getFiles(); |
||
96 | foreach ($files as $key => $file) { |
||
97 | if ($file->file == $filename) { |
||
98 | unlink($destination); |
||
99 | unset($files[$key]); |
||
100 | } |
||
101 | } |
||
102 | |||
103 | $files = array_values($files); |
||
104 | $this->repository->files = $files; |
||
105 | $this->save(); |
||
106 | } |
||
107 | } |
||
108 | |||
109 | /** |
||
110 | * @return string |
||
111 | */ |
||
112 | public function getFilesDir() |
||
116 | |||
117 | /** |
||
118 | * @param $a |
||
119 | * @param $b |
||
120 | * |
||
121 | * @return int |
||
122 | */ |
||
123 | private function compareFiles($a, $b) |
||
127 | |||
128 | protected function getDestinationPath() |
||
133 | } |
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.