SymfonyAdaptor::createSymfonyRouteCollection()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 0
cts 14
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
nop 1
crap 6
1
<?php
2
/**
3
 * This file is part of the DS Framework.
4
 *
5
 * (c) Dan Smith <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace Ds\Router\Adaptor;
11
12
use Ds\Router\Exceptions\RouterException;
13
use Ds\Router\Interfaces\RouteCollectionInterface;
14
use Ds\Router\Interfaces\RouteInterface;
15
use Ds\Router\Interfaces\SerializerInterface;
16
use Ds\Router\RouterResponse;
17
use Symfony\Component\Routing\Matcher\UrlMatcher;
18
use Symfony\Component\Routing\RequestContext;
19
use Symfony\Component\Routing\Route;
20
use Symfony\Component\Routing\RouteCollection;
21
22
/**
23
 * Class SymfonyAdaptor
24
 *
25
 * @package Ds\Router\Adaptor
26
 * @author  Dan Smith    <[email protected]>
27
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
28
 */
29
class SymfonyAdaptor extends AbstractAdaptor
30
{
31
    protected $locator;
32
    protected $context;
33
34
    /**
35
     * FastRouteAdaptor constructor.
36
     *
37
     * @param  SerializerInterface $serializer
38
     * @param  array $options
39
     * @throws RouterException
40
     */
41
    public function __construct(SerializerInterface $serializer, array $options = [])
42
    {
43
        parent::__construct($serializer);
44
45
        $this->options = $options;
46
47
        $this->context = new RequestContext('/');
48
49
        $routes = new RouteCollection();
50
51
        $routes->add('name',
52
            new Route('/foo', array('_controller' => 'MyController'))
53
        );
54
55
        $this->context = new RequestContext('/');
56
    }
57
58
    /**
59
     * Return RouterResponse for given route.
60
     *
61
     * @param  RouteCollectionInterface $routes
62
     * @param  string $method
63
     * @param  string $requestTarget
64
     * @return RouterResponse
65
     * @throws \Symfony\Component\Routing\Exception\ResourceNotFoundException
66
     * @throws \Symfony\Component\Routing\Exception\MethodNotAllowedException
67
     */
68
    public function match(RouteCollectionInterface $routes, $method, $requestTarget)
69
    {
70
        $response = ['response'];
71
        $symfonyRoutes = $this->createSymfonyRouteCollection($routes);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $symfonyRoutes is correct as $this->createSymfonyRouteCollection($routes) (which targets Ds\Router\Adaptor\Symfon...ymfonyRouteCollection()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
72
73
        $context = new RequestContext('/');
74
75
        $matcher = new UrlMatcher($symfonyRoutes, $context);
0 ignored issues
show
Documentation introduced by
$symfonyRoutes is of type null, but the function expects a object<Symfony\Component\Routing\RouteCollection>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
76
77
        $parameters = $matcher->match($requestTarget);
78
        // array('_controller' => 'MyController', '_route' => 'route_name')
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
79
80
        if (!isset($parameters['controller'])) {
81
            $response['statusCode'] = 404;
82
        }
83
84
        return $this->createRouterResponse($response);
85
    }
86
87
    public function createSymfonyRouteCollection(RouteCollectionInterface $routes)
88
    {
89
        $symfonyRoutes = new RouteCollection();
90
91
        foreach ($routes as $route) {
92
            $symfonyRoutes->add(
93
                \json_encode($route->getNames()),
94
                new Route(
95
                    $route->getPattern(),
96
                    [$route->getHandler()],
97
                    [],
98
                    [],
99
                    [],
0 ignored issues
show
Documentation introduced by
array() is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
100
                    [],
101
                    [$route->getMethod()]
102
                )
103
            );
104
        }
105
    }
106
107
    /**
108
     * Unserialize any cached content and return RouterResponse.
109
     *
110
     * @param  $dispatchResponse
111
     * @return RouterResponse
112
     */
113 View Code Duplication
    public function createRouterResponse($dispatchResponse)
0 ignored issues
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...
114
    {
115
        if ($dispatchResponse['handler']['type'] === 'object') {
116
            $dispatchResponse['content'] = $this->serializer->unserialize($dispatchResponse['handler']['content']);
117
        } else {
118
            $dispatchResponse['content'] = $dispatchResponse['handler']['content'];
119
        }
120
121
        return new RouterResponse(
122
            $dispatchResponse['statusCode'],
123
            $dispatchResponse['allowedMethods'],
124
            $dispatchResponse['content'],
0 ignored issues
show
Documentation introduced by
$dispatchResponse['content'] is of type object<Closure>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
125
            $dispatchResponse['vars'],
126
            $dispatchResponse['handler']['name']
0 ignored issues
show
Unused Code introduced by
The call to RouterResponse::__construct() has too many arguments starting with $dispatchResponse['handler']['name'].

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
127
        );
128
    }
129
130 View Code Duplication
    public function createFastRouteHandler(RouteInterface $route)
0 ignored issues
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...
131
    {
132
        $handlerOut = [
133
            'type' => $route->getHandlerType(),
134
            'name' => $route->getNames()
135
        ];
136
137
        if ($route->getHandlerType() === 'object') {
138
            $handlerOut['content'] = $this->serializer->serialize($route->getHandler());
0 ignored issues
show
Bug introduced by
It seems like $route->getHandler() targeting Ds\Router\Interfaces\RouteInterface::getHandler() can also be of type string; however, Ds\Router\Interfaces\Ser...rInterface::serialize() does only seem to accept object<Closure>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
139
        } else {
140
            $handlerOut['content'] = $route->getHandler();
141
        }
142
143
        return $handlerOut;
144
    }
145
146
    /**
147
     * Check if Cache Enabled and whether too skip adding routes.
148
     *
149
     * @return boolean
150
     */
151
    public function isCached()
152
    {
153
        return false;
154
    }
155
156
    /**
157
     * @inheritdoc
158
     */
159
    public function getCachedRoutes($context = '')
160
    {
161
        // TODO: Implement getCachedRoutes() method.
162
    }
163
}
164