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 |
||
| 12 | class PublicController extends ApiController { |
||
| 13 | |||
| 14 | private $db; |
||
| 15 | private $userManager; |
||
| 16 | |||
| 17 | 3 | public function __construct($appName, IRequest $request, IDb $db, Manager $userManager) { |
|
| 24 | |||
| 25 | /** |
||
| 26 | * @CORS |
||
| 27 | * @NoAdminRequired |
||
| 28 | * @NoCSRFRequired |
||
| 29 | */ |
||
| 30 | 3 | public function returnAsJson($user, $tags = array(), $conjunction = "or", $select = null, $sortby = "") { |
|
| 31 | |||
| 32 | 3 | if ($tags != null && $tags[0] == "") { |
|
| 33 | $tags = array(); |
||
| 34 | } |
||
| 35 | |||
| 36 | 3 | $attributesToSelect = array('url', 'title'); |
|
| 37 | |||
| 38 | 3 | if ($select != null) { |
|
| 39 | $attributesToSelect = array_merge($attributesToSelect, $select); |
||
| 40 | $attributesToSelect = array_unique($attributesToSelect); |
||
| 41 | } |
||
| 42 | |||
| 43 | 3 | $output = Bookmarks::findBookmarks($user, $this->db, 0, $sortby, $tags, true, -1, false, $attributesToSelect, $conjunction); |
|
| 44 | |||
| 45 | 3 | if (count($output) == 0) { |
|
| 46 | 2 | $output["status"] = 'error'; |
|
| 47 | 2 | $output["message"] = "No results from this query"; |
|
| 48 | 2 | return new JSONResponse($output); |
|
| 49 | } |
||
| 50 | |||
| 51 | 1 | return new JSONResponse($output); |
|
| 52 | } |
||
| 53 | |||
| 54 | |||
| 55 | /** |
||
| 56 | * @CORS |
||
| 57 | * @NoAdminRequired |
||
| 58 | * @NoCSRFRequired |
||
| 59 | */ |
||
| 60 | View Code Duplication | public function returnAddAsJson($user, $url = "", $tags = array(), $title = "", $description = "") { |
|
| 78 | |||
| 79 | /** |
||
| 80 | * @CORS |
||
| 81 | * @NoAdminRequired |
||
| 82 | * @NoCSRFRequired |
||
| 83 | */ |
||
| 84 | View Code Duplication | public function returnUpdateAsJson($user, $id, $url = "", $tags = array(), $title = "", $description = "") { |
|
| 102 | |||
| 103 | /** |
||
| 104 | * @CORS |
||
| 105 | * @NoAdminRequired |
||
| 106 | * @NoCSRFRequired |
||
| 107 | */ |
||
| 108 | public function returnDeleteAsJson($user, $id) { |
||
| 123 | |||
| 124 | /** |
||
| 125 | * @CORS |
||
| 126 | * @NoAdminRequired |
||
| 127 | * @NoCSRFRequired |
||
| 128 | */ |
||
| 129 | public function returnClickBookmarkAsJson($user, $url) { |
||
| 150 | |||
| 151 | public function newJsonErrorMessage($message) { |
||
| 157 | |||
| 158 | } |
||
| 159 |
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.