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 |
||
| 15 | class UrlGenerator implements UrlGeneratorContract |
||
| 16 | { |
||
| 17 | /** |
||
| 18 | * @var ServerRequestInterface |
||
| 19 | */ |
||
| 20 | private $request; |
||
| 21 | |||
| 22 | /** |
||
| 23 | * @var RouteCollection |
||
| 24 | */ |
||
| 25 | private $routes; |
||
| 26 | |||
| 27 | /** |
||
| 28 | * @var UriInterface |
||
| 29 | */ |
||
| 30 | private $uri; |
||
| 31 | |||
| 32 | /** |
||
| 33 | * UrlGenerator constructor. |
||
| 34 | * |
||
| 35 | * @param Request $request |
||
| 36 | * @param RouteCollection $routes |
||
| 37 | * @param UriInterface $uri |
||
| 38 | */ |
||
| 39 | public function __construct(Request $request, RouteCollection $routes, UriInterface $uri) |
||
| 45 | |||
| 46 | /** |
||
| 47 | * @inheritDoc |
||
| 48 | */ |
||
| 49 | View Code Duplication | public function toCurrent(array $variables = [], array $query = []): UriInterface |
|
| 61 | |||
| 62 | /** |
||
| 63 | * @inheritDoc |
||
| 64 | */ |
||
| 65 | View Code Duplication | public function toRoute(string $routeName, array $variables = [], array $query = []): UriInterface |
|
| 77 | |||
| 78 | /** |
||
| 79 | * Builds URI for provided route instance. |
||
| 80 | * |
||
| 81 | * @param Route $route |
||
| 82 | * @param array $variables |
||
| 83 | * @param array $query |
||
| 84 | * @return UriInterface |
||
| 85 | */ |
||
| 86 | private function buildRouteUri(Route $route, array $variables = [], array $query = []): UriInterface |
||
| 99 | } |
Let’s assume that you have a directory layout like this:
. |-- OtherDir | |-- Bar.php | `-- Foo.php `-- SomeDir `-- Foo.phpand let’s assume the following content of
Bar.php:If both files
OtherDir/Foo.phpandSomeDir/Foo.phpare loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.phpHowever, as
OtherDir/Foo.phpdoes not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: