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 |
||
| 5 | class APINoun extends Controller { |
||
| 6 | |||
| 7 | /** |
||
| 8 | * @var controller |
||
| 9 | */ |
||
| 10 | protected $parent = null; |
||
| 11 | |||
| 12 | /** |
||
| 13 | * @var DataObject |
||
| 14 | */ |
||
| 15 | protected $record = null; |
||
| 16 | |||
| 17 | /** |
||
| 18 | * @var Member |
||
| 19 | */ |
||
| 20 | protected $member = null; |
||
| 21 | |||
| 22 | /** |
||
| 23 | * Holds the url segment for this admin |
||
| 24 | * |
||
| 25 | * @param Controller|null $parent |
||
| 26 | * @param DataObject|null $record |
||
| 27 | */ |
||
| 28 | public function __construct(\Controller $parent = null, DataObject $record = null) { |
||
| 33 | |||
| 34 | /** |
||
| 35 | * Enable basic auth on the API |
||
| 36 | */ |
||
| 37 | public function init() { |
||
| 41 | |||
| 42 | /** |
||
| 43 | * @return DataObject |
||
| 44 | */ |
||
| 45 | public function getRecord() { |
||
| 48 | |||
| 49 | /** |
||
| 50 | * @return Member |
||
| 51 | */ |
||
| 52 | public function getMember() { |
||
| 55 | |||
| 56 | /** |
||
| 57 | * @param array $output |
||
| 58 | * @return SS_HTTPResponse |
||
| 59 | */ |
||
| 60 | View Code Duplication | protected function getAPIResponse($output) { |
|
|
|
|||
| 61 | $response = $this->getResponse(); |
||
| 62 | if($this->respondWithText()) { |
||
| 63 | $body = print_r($output, true); |
||
| 64 | $response->addHeader('Content-Type', 'text/plain'); |
||
| 65 | } else { |
||
| 66 | $body = Convert::raw2json($output); |
||
| 67 | $response->addHeader('Content-Type', 'application/json'); |
||
| 68 | } |
||
| 69 | $response->setBody($body); |
||
| 70 | return $response; |
||
| 71 | } |
||
| 72 | |||
| 73 | /** |
||
| 74 | * @return boolean |
||
| 75 | */ |
||
| 76 | View Code Duplication | protected function respondWithJSON() { |
|
| 85 | |||
| 86 | /** |
||
| 87 | * @return boolean |
||
| 88 | */ |
||
| 89 | View Code Duplication | protected function respondWithText() { |
|
| 98 | |||
| 99 | /** |
||
| 100 | * @return array|null |
||
| 101 | */ |
||
| 102 | protected function getRequestBody() { |
||
| 105 | |||
| 106 | /** |
||
| 107 | * Return a simple response with a message |
||
| 108 | * |
||
| 109 | * @param string $message |
||
| 110 | * @param int $statusCode |
||
| 111 | * @return SS_HTTPResponse |
||
| 112 | */ |
||
| 113 | protected function message($message, $statusCode) { |
||
| 121 | } |
||
| 122 |
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.