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 declare(strict_types = 1); |
||
17 | class UrlGenerator implements UrlGeneratorContract |
||
18 | { |
||
19 | /** |
||
20 | * @var ServerRequestInterface |
||
21 | */ |
||
22 | private $request; |
||
23 | |||
24 | /** |
||
25 | * @var RouteCollectionContract |
||
26 | */ |
||
27 | private $routes; |
||
28 | |||
29 | /** |
||
30 | * @var UriInterface |
||
31 | */ |
||
32 | private $uri; |
||
33 | |||
34 | /** |
||
35 | * UrlGenerator constructor. |
||
36 | * |
||
37 | * @param ServerRequestInterface $request |
||
38 | * @param RouteCollectionContract $routes |
||
39 | * @param UriInterface $uri |
||
40 | */ |
||
41 | 3 | public function __construct(ServerRequestInterface $request, RouteCollectionContract $routes, UriInterface $uri) |
|
47 | |||
48 | /** |
||
49 | * @inheritDoc |
||
50 | */ |
||
51 | 1 | View Code Duplication | public function toCurrent(array $variables = [], array $query = []): UriInterface |
52 | { |
||
53 | 1 | $route = $this->request->getAttribute('route'); |
|
54 | |||
55 | 1 | if ($route === null) { |
|
56 | throw new RouteNotFoundException( |
||
57 | sprintf('Unable to generate an URL for current.') |
||
58 | ); |
||
59 | } |
||
60 | |||
61 | 1 | return $this->buildRouteUri($route, $variables, $query); |
|
62 | } |
||
63 | |||
64 | /** |
||
65 | * @inheritDoc |
||
66 | */ |
||
67 | 1 | View Code Duplication | public function toRoute(string $routeName, array $variables = [], array $query = []): UriInterface |
68 | { |
||
69 | 1 | $route = $this->routes->findByName($routeName); |
|
70 | |||
71 | 1 | if ($route === null) { |
|
72 | throw new RouteNotFoundException( |
||
73 | sprintf('Unable to generate an URL for the named route "%s" as such route does not exist.', $routeName) |
||
74 | ); |
||
75 | } |
||
76 | |||
77 | 1 | return $this->buildRouteUri($route, $variables, $query); |
|
78 | } |
||
79 | |||
80 | /** |
||
81 | * Builds URI for provided route instance. |
||
82 | * |
||
83 | * @param RouteContract $route |
||
84 | * @param array $variables |
||
85 | * @param array $query |
||
86 | * @return UriInterface |
||
87 | */ |
||
88 | 2 | private function buildRouteUri(RouteContract $route, array $variables = [], array $query = []): UriInterface |
|
107 | } |
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)
or! empty(...)
instead.