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 |
||
31 | class FileMapper extends Mapper { |
||
32 | private $utils; |
||
33 | |||
34 | public function __construct(IDBConnection $db, Utils $utils) { |
||
35 | parent::__construct($db, 'passman_files'); |
||
36 | $this->utils = $utils; |
||
37 | } |
||
38 | |||
39 | |||
40 | /** |
||
41 | * @param $file_id |
||
42 | * @param null $user_id |
||
43 | * @return File |
||
44 | * @throws \OCP\AppFramework\Db\DoesNotExistException if not found |
||
45 | * @throws \OCP\AppFramework\Db\MultipleObjectsReturnedException if more than one result |
||
46 | */ |
||
47 | 1 | View Code Duplication | public function getFile($file_id, $user_id = null) { |
|
|||
48 | $sql = 'SELECT * FROM `*PREFIX*passman_files` ' . |
||
49 | 1 | 'WHERE `id` = ?'; |
|
50 | 1 | $params = [$file_id]; |
|
51 | 1 | if ($user_id !== null) { |
|
52 | 1 | $sql .= ' and `user_id` = ? '; |
|
53 | 1 | array_push($params, $user_id); |
|
54 | } |
||
55 | 1 | return $this->findEntity($sql, $params); |
|
56 | } |
||
57 | /** |
||
58 | * @param $file_id |
||
59 | * @param null $user_id |
||
60 | * @return File |
||
61 | * @throws \OCP\AppFramework\Db\DoesNotExistException if not found |
||
62 | * @throws \OCP\AppFramework\Db\MultipleObjectsReturnedException if more than one result |
||
63 | */ |
||
64 | 1 | View Code Duplication | public function getFileByGuid($file_guid, $user_id = null) { |
65 | $sql = 'SELECT * FROM `*PREFIX*passman_files` ' . |
||
66 | 1 | 'WHERE `guid` = ?'; |
|
67 | 1 | $params = [$file_guid]; |
|
68 | 1 | if ($user_id !== null) { |
|
69 | 1 | $sql .= ' and `user_id` = ? '; |
|
70 | 1 | array_push($params, $user_id); |
|
71 | } |
||
72 | 1 | return $this->findEntity($sql, $params); |
|
73 | } |
||
74 | |||
75 | /** |
||
76 | * @param $file_raw |
||
77 | * @param $userId |
||
78 | * @return File |
||
79 | */ |
||
80 | 1 | public function create($file_raw, $userId) { |
|
93 | |||
94 | /** |
||
95 | * Delete a file by file_id and user id |
||
96 | * @param $file_id |
||
97 | * @param $userId |
||
98 | * @return File |
||
99 | */ |
||
100 | 1 | public function deleteFile($file_id, $userId) { |
|
106 | |||
107 | /** |
||
108 | * Uodate file |
||
109 | * @param File $file |
||
110 | * @return File |
||
111 | */ |
||
112 | 1 | public function updateFile(File $file) { |
|
115 | } |
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.