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 |
||
| 11 | trait RouteAction |
||
| 12 | { |
||
| 13 | /** |
||
| 14 | * Get request, set for controller |
||
| 15 | * |
||
| 16 | * @return ServerRequestInterface |
||
| 17 | */ |
||
| 18 | abstract public function getRequest(); |
||
| 19 | |||
| 20 | /** |
||
| 21 | * Get response. set for controller |
||
| 22 | * |
||
| 23 | * @return ResponseInterface |
||
| 24 | */ |
||
| 25 | abstract public function getResponse(); |
||
| 26 | |||
| 27 | /** |
||
| 28 | * Respond with a server error |
||
| 29 | * |
||
| 30 | * @param string $message |
||
| 31 | * @param int $code HTTP status code |
||
| 32 | */ |
||
| 33 | abstract public function notFound($message = '', $code = 404); |
||
| 34 | |||
| 35 | /** |
||
| 36 | * Check if response is 2xx succesful, or empty |
||
| 37 | * |
||
| 38 | * @return boolean |
||
| 39 | */ |
||
| 40 | abstract public function isSuccessful(); |
||
| 41 | |||
| 42 | |||
| 43 | /** |
||
| 44 | * Get the route |
||
| 45 | * |
||
| 46 | * @return \stdClass |
||
| 47 | */ |
||
| 48 | 13 | protected function getRoute() |
|
| 67 | |||
| 68 | /** |
||
| 69 | * Get the method name of the action |
||
| 70 | * |
||
| 71 | * @param string $action |
||
| 72 | * @return string |
||
| 73 | */ |
||
| 74 | 11 | protected function getActionMethod($action) |
|
| 78 | |||
| 79 | /** |
||
| 80 | * Called before executing the action. |
||
| 81 | * If the response is no longer a success statuc (>= 300), the action will not be executed. |
||
| 82 | * |
||
| 83 | * <code> |
||
| 84 | * protected function beforeAction() |
||
| 85 | * { |
||
| 86 | * $this->respondWith('json'); // Respond with JSON by default |
||
| 87 | * |
||
| 88 | * if ($this->auth->getUser()->getCredits() <= 0) { |
||
| 89 | * $this->paymentRequired(); |
||
| 90 | * } |
||
| 91 | * } |
||
| 92 | * </code> |
||
| 93 | */ |
||
| 94 | 10 | protected function beforeAction() |
|
| 97 | |||
| 98 | /** |
||
| 99 | * Run the controller |
||
| 100 | * |
||
| 101 | * @return ResponseInterface |
||
| 102 | */ |
||
| 103 | 13 | public function run() |
|
| 121 | |||
| 122 | /** |
||
| 123 | * Get the arguments for a function from a route using reflection |
||
| 124 | * |
||
| 125 | * @param object $route |
||
| 126 | * @param \ReflectionFunctionAbstract $refl |
||
| 127 | * @return array |
||
| 128 | */ |
||
| 129 | 6 | protected function getFunctionArgs($route, \ReflectionFunctionAbstract $refl) |
|
| 153 | } |
||
| 154 |
For interface and abstract methods, it is impossible to infer the return type from the immediate code. In these cases, it is generally advisible to explicitly annotate these methods with a
@returndoc comment to communicate to implementors of these methods what they are expected to return.