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 |
||
| 38 | class OCSMiddleware extends Middleware { |
||
| 39 | |||
| 40 | /** @var IRequest */ |
||
| 41 | private $request; |
||
| 42 | |||
| 43 | /** |
||
| 44 | * @param IRequest $request |
||
| 45 | */ |
||
| 46 | public function __construct(IRequest $request) { |
||
| 49 | |||
| 50 | /** |
||
| 51 | * @param \OCP\AppFramework\Controller $controller |
||
| 52 | * @param string $methodName |
||
| 53 | * @param \Exception $exception |
||
| 54 | * @throws \Exception |
||
| 55 | * @return OCSResponse |
||
| 56 | */ |
||
| 57 | public function afterException($controller, $methodName, \Exception $exception) { |
||
| 98 | |||
| 99 | /** |
||
| 100 | * @param \OCP\AppFramework\Controller $controller |
||
| 101 | * @param string $methodName |
||
| 102 | * @param Response $response |
||
| 103 | * @return \OCP\AppFramework\Http\Response |
||
| 104 | */ |
||
| 105 | public function afterController($controller, $methodName, Response $response) { |
||
| 106 | /* |
||
| 107 | * If a different middleware has detected that a request unauthorized or forbidden |
||
| 108 | * we need to catch the response and convert it to a proper OCS response. |
||
| 109 | */ |
||
| 110 | if ($controller instanceof OCSController && !($response instanceof OCSResponse)) { |
||
| 111 | if ($response->getStatus() === Http::STATUS_UNAUTHORIZED || |
||
| 112 | $response->getStatus() === Http::STATUS_FORBIDDEN) { |
||
| 113 | $format = $this->getFormat($controller); |
||
| 114 | |||
| 115 | $message = ''; |
||
| 116 | if ($response instanceof JSONResponse) { |
||
| 117 | /** @var DataResponse $response */ |
||
| 118 | $message = $response->getData()['message']; |
||
| 119 | } |
||
| 120 | $response = new OCSResponse($format, \OCP\API::RESPOND_UNAUTHORISED, $message); |
||
| 121 | $response->setStatus(Http::STATUS_UNAUTHORIZED); |
||
| 122 | } |
||
| 123 | } |
||
| 124 | |||
| 125 | return $response; |
||
| 126 | } |
||
| 127 | |||
| 128 | /** |
||
| 129 | * @param \OCP\AppFramework\Controller $controller |
||
| 130 | * @return string |
||
| 131 | */ |
||
| 132 | private function getFormat($controller) { |
||
| 144 | } |
||
| 145 |
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.