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 |
||
| 18 | trait Searchable |
||
| 19 | { |
||
| 20 | use HandlesRequest; |
||
| 21 | |||
| 22 | protected $moduleSearchPage = 'SearchPage'; |
||
| 23 | |||
| 24 | /** |
||
| 25 | * @return string |
||
| 26 | */ |
||
| 27 | protected function getSearchScope() |
||
| 31 | |||
| 32 | /** |
||
| 33 | * Executes search to API. Query - search string. |
||
| 34 | * |
||
| 35 | * @param string $query |
||
| 36 | * @param string $scope |
||
| 37 | * @param array $bookmarks |
||
| 38 | * |
||
| 39 | * @return SearchResponse |
||
| 40 | */ |
||
| 41 | public function execSearchRequest($query, $scope, $bookmarks = []) |
||
| 42 | { |
||
| 43 | $url = UrlBuilder::getSearchUrl($bookmarks); |
||
| 44 | $get = $this->createSearchQuery($query, $scope, $bookmarks); |
||
| 45 | $result = $this->request->exec($url . '?' . $get); |
||
| 46 | |||
| 47 | $this->processResult($result); |
||
| 48 | |||
| 49 | return new SearchResponse($this->response); |
||
| 50 | } |
||
| 51 | |||
| 52 | /** |
||
| 53 | * Creates Pinterest API search request. |
||
| 54 | * |
||
| 55 | * @param string $query |
||
| 56 | * @param string $scope |
||
| 57 | * @param array $bookmarks |
||
| 58 | * |
||
| 59 | * @return string |
||
| 60 | */ |
||
| 61 | protected function createSearchQuery($query, $scope, $bookmarks = []) |
||
| 75 | |||
| 76 | /** |
||
| 77 | * Search entities by search query. |
||
| 78 | * |
||
| 79 | * @param string $query |
||
| 80 | * @param int $limit |
||
| 81 | * |
||
| 82 | * @return Pagination |
||
| 83 | */ |
||
| 84 | View Code Duplication | public function search($query, $limit = Pagination::DEFAULT_LIMIT) |
|
|
|
|||
| 85 | { |
||
| 86 | return (new Pagination($limit)) |
||
| 87 | ->paginateOver(function($bookmarks = []) use ($query) { |
||
| 88 | return $this->execSearchRequest($query, $this->getSearchScope(), $bookmarks); |
||
| 89 | }); |
||
| 90 | } |
||
| 91 | |||
| 92 | /** |
||
| 93 | * @param array $bookmarks |
||
| 94 | * @param array $options |
||
| 95 | * |
||
| 96 | * @return array |
||
| 97 | */ |
||
| 98 | protected function appendBookMarks($bookmarks, $options) |
||
| 118 | |||
| 119 | /** |
||
| 120 | * @param string $res |
||
| 121 | * @return Response |
||
| 122 | */ |
||
| 123 | abstract protected function processResult($res); |
||
| 124 | } |
||
| 125 |
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.