Completed
Push — master ( 82f763...87fa0d )
by Joschi
06:38
created

AuraRouterAdapter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 1

Importance

Changes 4
Bugs 1 Features 0
Metric Value
c 4
b 1
f 0
dl 0
loc 14
ccs 10
cts 10
cp 1
rs 9.4285
cc 1
eloc 8
nc 1
nop 1
crap 1
1
<?php
2
3
/**
4
 * apparat-server
5
 *
6
 * @category    Apparat
7
 * @package     Apparat\Server
8
 * @subpackage  Apparat\Server\Infrastructure
9
 * @author      Joschi Kuphal <[email protected]> / @jkphl
10
 * @copyright   Copyright © 2016 Joschi Kuphal <[email protected]> / @jkphl
11
 * @license     http://opensource.org/licenses/MIT The MIT License (MIT)
12
 */
13
14
/***********************************************************************************
15
 *  The MIT License (MIT)
16
 *
17
 *  Copyright © 2016 Joschi Kuphal <[email protected]> / @jkphl
18
 *
19
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
20
 *  this software and associated documentation files (the "Software"), to deal in
21
 *  the Software without restriction, including without limitation the rights to
22
 *  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
23
 *  the Software, and to permit persons to whom the Software is furnished to do so,
24
 *  subject to the following conditions:
25
 *
26
 *  The above copyright notice and this permission notice shall be included in all
27
 *  copies or substantial portions of the Software.
28
 *
29
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
31
 *  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
32
 *  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
33
 *  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
34
 *  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35
 ***********************************************************************************/
36
37
namespace Apparat\Server\Infrastructure\Route;
38
39
use Apparat\Kernel\Ports\Kernel;
40
use Apparat\Server\Domain\Contract\ActionRouteInterface;
41
use Apparat\Server\Domain\Contract\RouteInterface;
42
use Apparat\Server\Domain\Contract\RouterContainerInterface;
43
use Apparat\Server\Ports\Action\ActionInterface;
44
use Aura\Router\RouterContainer;
45
use Aura\Router\Rule;
46
use Psr\Http\Message\ResponseInterface;
47
use Psr\Http\Message\ServerRequestInterface;
48
49
/**
50
 * Aura.Router adapter
51
 *
52
 * @package Apparat\Server
53
 * @subpackage Apparat\Server\Infrastructure
54
 */
55
class AuraRouterAdapter implements RouterContainerInterface
56
{
57
    /**
58
     * Aura.Router container
59
     *
60
     * @var RouterContainer
61
     */
62
    protected $routerContainer;
63
64
    /**
65
     * Constructor
66
     *
67
     * @param RouterContainer $routerContainer Router container
68
     */
69 5
    public function __construct(RouterContainer $routerContainer)
70
    {
71 5
        $this->routerContainer = $routerContainer;
72
73
        // Override the default rules
74
        /** @var Rule\RuleIterator $ruleIterator */
75 5
        $ruleIterator = $routerContainer->getRuleIterator();
76 5
        $ruleIterator->set([
77 5
            new Rule\Secure(),
78 5
            new Rule\Host(),
79 5
            new Rule\Allows(),
80 5
            new Rule\Accepts(),
81 5
        ]);
82 5
    }
83
84
    /**
85
     * Register a route
86
     *
87
     * @param RouteInterface $route Route
88
     * @return RouterContainerInterface Self reference
89
     */
90 5
    public function registerRoute(RouteInterface $route)
91
    {
92
        /** @var AuraRoute $auraRoute */
93 5
        $auraRoute = $route->isObject() ? $this->createAuraObjectRoute() : $this->createAuraRoute();
94 5
        $auraRoute->name($route->getName())
95 5
            ->path($route->getPath())
96 5
            ->allows($route->getVerbs())
97 5
            ->handler($route->getAction())
98 5
            ->tokens($route->getTokens())
99 5
            ->defaults($route->getDefaults())
100 5
            ->wildcard($route->getWildcard())
101 5
            ->host($route->getHost())
102 5
            ->accepts($route->getAccepts())
103 5
            ->auth($route->getAuth())
104 5
            ->secure($route->getSecure())
0 ignored issues
show
Bug introduced by
It seems like $route->getSecure() targeting Apparat\Server\Domain\Co...eInterface::getSecure() can also be of type null; however, Aura\Router\Route::secure() does only seem to accept boolean, 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...
105 5
            ->extras($route->getExtras());
106 5
        $this->routerContainer->getMap()->addRoute($auraRoute);
107
108 5
        return $this;
109
    }
110
111
    /**
112
     * Instantiate and register an aura object route
113
     *
114
     * @return AuraObjectRoute Aura object route
115
     */
116 77
    protected function createAuraObjectRoute()
117 77
    {
118 2
        $ruleIterator = $this->routerContainer->getRuleIterator();
119 2
        $ruleIterator->append(new ObjectPath(rtrim(parse_url(getenv('APPARAT_BASE_URL'), PHP_URL_PATH), '/') ?: null));
120 2
        return Kernel::create(AuraObjectRoute::class);
121
    }
122
123
    /**
124
     * Instantiate and register an aura object route
125
     *
126
     * @return AuraRoute Aura route
127
     */
128 3
    protected function createAuraRoute()
129
    {
130 3
        $ruleIterator = $this->routerContainer->getRuleIterator();
131 3
        $ruleIterator->append(new Rule\Path(rtrim(parse_url(getenv('APPARAT_BASE_URL'), PHP_URL_PATH), '/') ?: null));
132 3
        return Kernel::create(AuraRoute::class);
133
    }
134
135
    /**
136
     * Dispatch a request to a route
137
     *
138
     * @param ServerRequestInterface $request
139
     * @return AbstractActionRoute $route
140
     */
141 77
    public function dispatchRequestToRoute(ServerRequestInterface $request)
142
    {
143 77
        $matcher = $this->routerContainer->getMatcher();
144 77
        $route = $matcher->match($request);
145
146
        // If a matching route was found
147 77
        if ($route instanceof ActionRouteInterface) {
148 72
            return $route;
149
        }
150
151
        // Else create an error route
152 5
        return AuraErrorRoute::cast($matcher->getFailedRoute());
153
    }
154
155
    /**
156
     * Prepare and return a route action
157
     *
158
     * @param ServerRequestInterface $request Request
159
     * @param AbstractActionRoute $route Route
160
     * @return ActionInterface|Callable $action Action
161
     */
162 77
    public function getRouteAction(ServerRequestInterface $request, AbstractActionRoute $route)
163
    {
164
        // Pre-process the matched attributes
165 77
        $route->preprocessAttributes();
166
167
        // Copy all route attributes to the server request
168 77
        foreach ($route->attributes as $key => $val) {
169 76
            $request = $request->withAttribute($key, $val);
170 77
        }
171
172
        /** @var AbstractActionRoute $route */
173 77
        $handler = $route->getHandler();
174
175
        // If the handler is a callable
176 76
        if (is_callable($handler)) {
177 1
            return function () use ($handler, $request) {
178
                /** @var ResponseInterface $response */
179 1
                $response = $handler($request);
180 1
                return $response;
181 1
            };
182
        }
183
184 75
        return Kernel::create($handler, [$request]);
0 ignored issues
show
Bug introduced by
It seems like $handler defined by $route->getHandler() on line 173 can also be of type object<Apparat\Server\Do...ntract\ActionInterface>; however, Apparat\Kernel\Ports\Kernel::create() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
185
    }
186
}
187