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 |
||
| 24 | class RestController extends Controller |
||
| 25 | { |
||
| 26 | |||
| 27 | const MIME_TYPE_JSON = 'application/json'; |
||
| 28 | |||
| 29 | 41 | public function respond(AbstractApiResponse $apiResponse): Response |
|
| 38 | |||
| 39 | 4 | protected function createAndProcessForm( |
|
| 50 | |||
| 51 | /** |
||
| 52 | * Process form |
||
| 53 | * @param Request $request |
||
| 54 | * @param FormInterface $form |
||
| 55 | */ |
||
| 56 | 15 | protected function processForm(Request $request, FormInterface $form) |
|
| 63 | |||
| 64 | /** {@inheritDoc} */ |
||
| 65 | 8 | protected function createFormBuilder($data = null, array $options = []): FormBuilder |
|
| 71 | |||
| 72 | /** |
||
| 73 | * Create collection api response with total, limit and offset parameters |
||
| 74 | * @param integer|null $limit |
||
| 75 | * @param integer|null $offset |
||
| 76 | */ |
||
| 77 | 4 | protected function listEntities(AbstractRepository $repository, $limit, $offset): Response |
|
| 89 | |||
| 90 | /** |
||
| 91 | * @param string $entityFullName Entity class name |
||
| 92 | * @param string|int $id Entity id |
||
| 93 | * @return ApiError |
||
| 94 | * @throws EntityNotFoundException |
||
| 95 | */ |
||
| 96 | 5 | protected function createEntityNotFoundResponse(string $entityFullName, $id): ApiError |
|
| 100 | |||
| 101 | /** |
||
| 102 | * @param string|int $id |
||
| 103 | */ |
||
| 104 | 14 | View Code Duplication | protected function viewEntity(AbstractRepository $repository, $id): Response |
| 117 | |||
| 118 | 41 | private function setLocation(Response $response, AbstractApiResponse $apiResponse) |
|
| 124 | |||
| 125 | 41 | private function setContentType(AbstractApiResponse $apiResponse, Response $response) |
|
| 131 | |||
| 132 | /** |
||
| 133 | * Create ApiOperation from Request method |
||
| 134 | */ |
||
| 135 | 4 | protected function createApiOperation(Request $request): ApiOperation |
|
| 139 | } |
||
| 140 |
This check looks for a call to a parent method whose name is different than the method from which it is called.
Consider the following code:
The
getFirstName()method in theSoncalls the wrong method in the parent class.