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:
Complex classes like Dispatcher often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Dispatcher, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 26 | class Dispatcher |
||
| 27 | { |
||
| 28 | /** |
||
| 29 | * Dispatcher default options. |
||
| 30 | * |
||
| 31 | * @var array |
||
| 32 | */ |
||
| 33 | protected static $defaults = [ |
||
| 34 | 'stringHandlerPattern' => '::', |
||
| 35 | 'autoWire' => true |
||
| 36 | ]; |
||
| 37 | /** |
||
| 38 | * @var array |
||
| 39 | */ |
||
| 40 | private $options; |
||
| 41 | /** |
||
| 42 | * @var array |
||
| 43 | */ |
||
| 44 | private $providedArguments; |
||
| 45 | /** |
||
| 46 | * @var array |
||
| 47 | */ |
||
| 48 | private $constructParams; |
||
| 49 | |||
| 50 | /** |
||
| 51 | * Handler Class Namespaces. |
||
| 52 | * |
||
| 53 | * @var array. |
||
| 54 | */ |
||
| 55 | private $namespaces = []; |
||
| 56 | |||
| 57 | /** |
||
| 58 | * Dispatcher constructor. |
||
| 59 | * |
||
| 60 | * @param array $options |
||
| 61 | */ |
||
| 62 | 2 | public function __construct(array $options = array()) |
|
| 67 | |||
| 68 | /** |
||
| 69 | * Get response from handler string. |
||
| 70 | * |
||
| 71 | * @param $request |
||
| 72 | * @param string|\Closure $handler |
||
| 73 | * @param array $constructor |
||
| 74 | * @return ResponseInterface |
||
| 75 | * @throws \Exception |
||
| 76 | */ |
||
| 77 | public function dispatch(ServerRequestInterface $request, $handler, array $constructor = array()) |
||
| 78 | { |
||
| 79 | $handlerType = \gettype($handler); |
||
| 80 | $response = null; |
||
| 81 | |||
| 82 | switch ($handlerType) { |
||
| 83 | case 'string': |
||
|
|
|||
| 84 | |||
| 85 | $params = \explode($this->options['stringHandlerPattern'], $handler); |
||
| 86 | if (!isset($params[1])){ |
||
| 87 | $response = $handler; |
||
| 88 | break; |
||
| 89 | } |
||
| 90 | |||
| 91 | $resolvedHandler = $this->_processStringHandler($handler); |
||
| 92 | $this->_getParams($resolvedHandler['controller'], $constructor); |
||
| 93 | $response = $this->_callController($request, $resolvedHandler['controller'], $resolvedHandler['method']); |
||
| 94 | break; |
||
| 95 | case 'object': |
||
| 96 | if (\is_callable($handler)) { |
||
| 97 | $response = $handler($request); |
||
| 98 | } |
||
| 99 | break; |
||
| 100 | default: |
||
| 101 | throw new DispatchException( |
||
| 102 | "Handler type: {$handlerType} is not valid." |
||
| 103 | ); |
||
| 104 | } |
||
| 105 | |||
| 106 | if (!$response instanceof ResponseInterface) { |
||
| 107 | $response = $this->createNewResponse($response); |
||
| 108 | } |
||
| 109 | return $response; |
||
| 110 | } |
||
| 111 | |||
| 112 | /*** |
||
| 113 | * Get Controller/Method from handler string. |
||
| 114 | * |
||
| 115 | * @param $handler |
||
| 116 | * @return mixed |
||
| 117 | * @throws DispatchException |
||
| 118 | */ |
||
| 119 | protected function _processStringHandler($handler) |
||
| 120 | { |
||
| 121 | $controllerMethod = \explode( |
||
| 122 | $this->options['stringHandlerPattern'], $handler |
||
| 123 | ); |
||
| 124 | |||
| 125 | try { |
||
| 126 | $resolvedHandler['controller'] = $this->_findClass($controllerMethod[0]); |
||
| 127 | } catch (\Exception $e) { |
||
| 128 | throw new DispatchException($e->getMessage()); |
||
| 129 | } |
||
| 130 | |||
| 131 | $resolvedHandler['method'] = $controllerMethod[1] ?? null; |
||
| 132 | |||
| 133 | return $resolvedHandler; |
||
| 134 | } |
||
| 135 | |||
| 136 | /** |
||
| 137 | * Find class from namespace. |
||
| 138 | * |
||
| 139 | * @param string $class |
||
| 140 | * @return string |
||
| 141 | * @throws DispatchException |
||
| 142 | */ |
||
| 143 | protected function _findClass($class) |
||
| 144 | { |
||
| 145 | if (\class_exists($class)) { |
||
| 146 | return $class; |
||
| 147 | } |
||
| 148 | |||
| 149 | foreach ($this->namespaces as $namespace) { |
||
| 150 | if (\class_exists($namespace . $class)) { |
||
| 151 | return $namespace . $class; |
||
| 152 | } |
||
| 153 | } |
||
| 154 | |||
| 155 | throw new DispatchException("Controller : {$class} does not exist"); |
||
| 156 | } |
||
| 157 | |||
| 158 | /** |
||
| 159 | * Find class construct parameters from provided arguments. |
||
| 160 | * |
||
| 161 | * @param string $controllerName |
||
| 162 | * @param array $args |
||
| 163 | * @return array |
||
| 164 | * @throws DispatchException |
||
| 165 | */ |
||
| 166 | protected function _getParams(string $controllerName, array $args) |
||
| 167 | { |
||
| 168 | if ($this->options['autoWire'] === false) { |
||
| 169 | $this->providedArguments = $args; |
||
| 170 | return $this->providedArguments; |
||
| 171 | } |
||
| 172 | |||
| 173 | $this->providedArguments = []; |
||
| 174 | $this->constructParams = $this->_getConstructParams($controllerName); |
||
| 175 | |||
| 176 | try { |
||
| 177 | $this->_getParamsFromVariableName($args); |
||
| 178 | } catch (\Exception $e) { |
||
| 179 | $this->_getParamsFromTypeHint($args); |
||
| 180 | } |
||
| 181 | |||
| 182 | View Code Duplication | if (\count($this->providedArguments) - \count($this->constructParams) > 0) { |
|
| 183 | throw new DispatchException('Missing parameters'); |
||
| 184 | } |
||
| 185 | |||
| 186 | \ksort($this->providedArguments); |
||
| 187 | return $this->providedArguments; |
||
| 188 | } |
||
| 189 | |||
| 190 | /** |
||
| 191 | * Reflect Controller construct and get parameters. |
||
| 192 | * |
||
| 193 | * @param $controllerName |
||
| 194 | * @internal |
||
| 195 | * |
||
| 196 | * @return \ReflectionParameter[] |
||
| 197 | */ |
||
| 198 | protected function _getConstructParams($controllerName) |
||
| 199 | { |
||
| 200 | $controllerReflection = new \ReflectionClass($controllerName); |
||
| 201 | $constructor = $controllerReflection->getConstructor(); |
||
| 202 | |||
| 203 | if (null === $constructor) { |
||
| 204 | return []; |
||
| 205 | } |
||
| 206 | |||
| 207 | return $constructor->getParameters(); |
||
| 208 | } |
||
| 209 | |||
| 210 | /** |
||
| 211 | * Find controller constructor params based on $arg[index] |
||
| 212 | * |
||
| 213 | * @param $args |
||
| 214 | * @throws DispatchException |
||
| 215 | */ |
||
| 216 | protected function _getParamsFromVariableName($args) |
||
| 217 | { |
||
| 218 | foreach ($this->constructParams as $index => $param) { |
||
| 219 | $parameterVarName = $param->getName(); |
||
| 220 | $constructorParamIndex = (int)$param->getPosition(); |
||
| 221 | |||
| 222 | if (isset($args[$parameterVarName])) { |
||
| 223 | $this->providedArguments[$constructorParamIndex] = $args[$parameterVarName]; |
||
| 224 | } |
||
| 225 | } |
||
| 226 | View Code Duplication | if (\count($this->constructParams) - \count($this->providedArguments) > 0) { |
|
| 227 | throw new DispatchException('Missing parameters'); |
||
| 228 | } |
||
| 229 | } |
||
| 230 | |||
| 231 | /** |
||
| 232 | * Find missing parameters based on Class name or type hint. |
||
| 233 | * |
||
| 234 | * @param $args |
||
| 235 | */ |
||
| 236 | protected function _getParamsFromTypeHint($args) |
||
| 237 | { |
||
| 238 | $processedArgs = $this->_processConstructArgs($args); |
||
| 239 | |||
| 240 | foreach ($this->constructParams as $index => $param) { |
||
| 241 | |||
| 242 | /** |
||
| 243 | * @var \ReflectionClass $constructorParamClass ; |
||
| 244 | */ |
||
| 245 | $constructorParamClass = $param->getClass(); |
||
| 246 | $constructorParamIndex = (int)$param->getPosition(); |
||
| 247 | |||
| 248 | if (isset($this->providedArguments[$constructorParamIndex])) { |
||
| 249 | continue; |
||
| 250 | } |
||
| 251 | |||
| 252 | if ($constructorParamClass) { |
||
| 253 | $constructParamTypeHint = $constructorParamClass->getName(); |
||
| 254 | foreach ((array)$processedArgs['object'] as $useParam) { |
||
| 255 | $key = \array_search($constructParamTypeHint, $useParam['interfaces'], true); |
||
| 256 | if ($key !== false) { |
||
| 257 | $this->providedArguments[$constructorParamIndex] = $useParam['value']; |
||
| 258 | } |
||
| 259 | } |
||
| 260 | } |
||
| 261 | } |
||
| 262 | } |
||
| 263 | |||
| 264 | /** |
||
| 265 | * Process provided arguments. |
||
| 266 | * |
||
| 267 | * @param array $args |
||
| 268 | * @return array |
||
| 269 | */ |
||
| 270 | protected function _processConstructArgs(array $args = []) |
||
| 271 | { |
||
| 272 | $arguments = []; |
||
| 273 | foreach ($args as $index => $param) { |
||
| 274 | switch (\gettype($param)) { |
||
| 275 | case 'object': |
||
| 276 | $arguments['object'][] = [ |
||
| 277 | 'class' => \get_class($param), |
||
| 278 | 'interfaces' => \class_implements($param), |
||
| 279 | 'value' => $param |
||
| 280 | ]; |
||
| 281 | break; |
||
| 282 | } |
||
| 283 | } |
||
| 284 | return $arguments; |
||
| 285 | } |
||
| 286 | |||
| 287 | /** |
||
| 288 | * Call controller with provided request and return Response. |
||
| 289 | * |
||
| 290 | * @param ServerRequestInterface $request Server Request |
||
| 291 | * @param string $controller Controller class. |
||
| 292 | * @param string $method Controller method. |
||
| 293 | * |
||
| 294 | * @return ResponseInterface |
||
| 295 | * @throws DispatchException |
||
| 296 | */ |
||
| 297 | protected function _callController(ServerRequestInterface $request, string $controller, string $method) |
||
| 298 | { |
||
| 299 | |||
| 300 | if (!class_exists($controller)){ |
||
| 301 | throw new DispatchException('Unable to locate controller: '.$controller); |
||
| 302 | } |
||
| 303 | |||
| 304 | $controllerObj = new $controller(...$this->providedArguments); |
||
| 305 | |||
| 306 | try { |
||
| 307 | $this->_checkWhiteList($controller, $this->options); |
||
| 308 | $this->_checkBlackList($controller, $this->options); |
||
| 309 | } catch (\Exception $e) { |
||
| 310 | unset($controllerObj); |
||
| 311 | throw new DispatchException($e->getMessage()); |
||
| 312 | } |
||
| 313 | |||
| 314 | if (!method_exists($controllerObj,$method)){ |
||
| 315 | throw new DispatchException('Unable to locate method: '.$controller.'::'.$method); |
||
| 316 | } |
||
| 317 | |||
| 318 | return $controllerObj->{$method}($request); |
||
| 319 | } |
||
| 320 | |||
| 321 | /** |
||
| 322 | * Checks controller instance against whitelist. |
||
| 323 | * |
||
| 324 | * @param $controller |
||
| 325 | * @param $options |
||
| 326 | * @throws DispatchException |
||
| 327 | */ |
||
| 328 | View Code Duplication | protected function _checkWhiteList($controller, $options) |
|
| 329 | { |
||
| 330 | if (isset($options['blacklist'])) { |
||
| 331 | if (!$this->_checkInList($controller, $options['blacklist'])) { |
||
| 332 | throw new DispatchException("Controller: {$controller}, not part of allowed whitelist."); |
||
| 333 | } |
||
| 334 | } |
||
| 335 | } |
||
| 336 | |||
| 337 | /** |
||
| 338 | * Internal function for checking controller instance against class list. |
||
| 339 | * |
||
| 340 | * @param $controller |
||
| 341 | * @param array $classList |
||
| 342 | * @internal |
||
| 343 | * @return bool |
||
| 344 | */ |
||
| 345 | protected function _checkInList($controller, array $classList) |
||
| 346 | { |
||
| 347 | foreach ((array)$classList as $classes) { |
||
| 348 | if ($controller instanceof $classes) { |
||
| 349 | return true; |
||
| 350 | } |
||
| 351 | } |
||
| 352 | return false; |
||
| 353 | } |
||
| 354 | |||
| 355 | /** |
||
| 356 | * Checks controller instance against blacklist. |
||
| 357 | * |
||
| 358 | * @param $controller |
||
| 359 | * @param $options |
||
| 360 | * @throws DispatchException |
||
| 361 | */ |
||
| 362 | View Code Duplication | protected function _checkBlackList($controller, $options) |
|
| 363 | { |
||
| 364 | if (isset($options['blacklist'])) { |
||
| 365 | if ($this->_checkInList($controller, $options['blacklist'])) { |
||
| 366 | throw new DispatchException("Controller: {$controller}, found on blacklist."); |
||
| 367 | } |
||
| 368 | } |
||
| 369 | } |
||
| 370 | |||
| 371 | /** |
||
| 372 | * Create a new PSR-7 Response. |
||
| 373 | * |
||
| 374 | * @param $controllerResponse |
||
| 375 | * @return Response |
||
| 376 | * @throws \InvalidArgumentException |
||
| 377 | */ |
||
| 378 | public function createNewResponse($controllerResponse) |
||
| 379 | { |
||
| 380 | $response = new Response(); |
||
| 381 | $body = new Stream("php://memory", "wb+"); |
||
| 382 | $body->write($controllerResponse); |
||
| 383 | $body->rewind(); |
||
| 384 | return $response->withBody($body); |
||
| 385 | } |
||
| 386 | |||
| 387 | /** |
||
| 388 | * With Class Namespace. |
||
| 389 | * |
||
| 390 | * @param $namespace |
||
| 391 | * @return Dispatcher |
||
| 392 | */ |
||
| 393 | 1 | public function withNamespace($namespace) |
|
| 399 | |||
| 400 | /** |
||
| 401 | * With class Namespaces. |
||
| 402 | * |
||
| 403 | * @param array $namespaces |
||
| 404 | * @return Dispatcher |
||
| 405 | */ |
||
| 406 | 1 | public function withNamespaces(array $namespaces) |
|
| 407 | { |
||
| 408 | 1 | $new = clone $this; |
|
| 409 | 1 | foreach ($namespaces as $ns) { |
|
| 410 | 1 | $new->namespaces[$ns] = $ns; |
|
| 411 | } |
||
| 412 | 1 | return $new; |
|
| 414 | } |
||
| 415 |
According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.
}
To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.