Test Failed
Push — master ( ae28f9...7916f9 )
by Vsevolods
03:53
created

UrlGenerator   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 85
Duplicated Lines 28.24 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 24
loc 85
c 0
b 0
f 0
wmc 9
lcom 1
cbo 5
ccs 0
cts 37
cp 0
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A toCurrent() 12 12 2
A toRoute() 12 12 2
A buildRouteUri() 0 13 4

How to fix   Duplicated Code   

Duplicated Code

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
2
3
4
namespace Venta\Routing;
5
6
7
use Psr\Http\Message\ServerRequestInterface;
8
use Psr\Http\Message\UriInterface;
9
use Venta\Contracts\Http\Request;
10
use Venta\Contracts\Routing\Route;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Venta\Routing\Route.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are 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.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/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:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
11
use Venta\Contracts\Routing\RouteCollection;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Venta\Routing\RouteCollection.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are 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.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/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:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
12
use Venta\Contracts\Routing\UrlGenerator as UrlGeneratorContract;
13
use Venta\Routing\Exception\RouteNotFoundException;
14
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)
40
    {
41
        $this->request = $request;
42
        $this->routes = $routes;
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
43
        $this->uri = $uri;
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 5 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
44
    }
45
46
    /**
47
     * @inheritDoc
48
     */
49 View Code Duplication
    public function toCurrent(array $variables = [], array $query = []): UriInterface
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
50
    {
51
        $route = $this->request->getRoute();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Http\Message\ServerRequestInterface as the method getRoute() does only exist in the following implementations of said interface: Venta\Http\Request.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
52
53
        if ($route === null) {
54
            throw new RouteNotFoundException(
55
                sprintf('Unable to generate an URL for current.')
56
            );
57
        }
58
59
        return $this->buildRouteUri($route, $variables, $query);
60
    }
61
62
    /**
63
     * @inheritDoc
64
     */
65 View Code Duplication
    public function toRoute(string $routeName, array $variables = [], array $query = []): UriInterface
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
66
    {
67
        $route = $this->routes->findByName($routeName);
68
69
        if ($route === null) {
70
            throw new RouteNotFoundException(
71
                sprintf('Unable to generate an URL for the named route "%s" as such route does not exist.', $routeName)
72
            );
73
        }
74
75
        return $this->buildRouteUri($route, $variables, $query);
76
    }
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
87
    {
88
        $uri = $this->uri
89
            ->withScheme($route->getScheme() ?: $this->request->getUri()->getScheme())
90
            ->withHost($route->getHost() ?: $this->request->getUri()->getHost())
91
            ->withPath($route->compilePath($variables));
92
93
        if ($query) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $query of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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.

Loading history...
94
            $uri = $uri->withQuery(http_build_query($query));
95
        }
96
97
        return $uri;
98
    }
99
}