Completed
Push — 4.0 ( 19a36c...8b2e11 )
by Olivier
07:31
created

RouteDispatcher::resolve_controller()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 20
rs 9.4285
1
<?php
2
3
/*
4
 * This file is part of the ICanBoogie package.
5
 *
6
 * (c) Olivier Laviale <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ICanBoogie\Routing;
13
14
use ICanBoogie\Accessor\AccessorTrait;
15
use ICanBoogie\HTTP\Dispatcher;
16
use ICanBoogie\HTTP\RedirectResponse;
17
use ICanBoogie\HTTP\Request;
18
use ICanBoogie\HTTP\Response;
19
use ICanBoogie\HTTP\Status;
20
use ICanBoogie\Routing\RouteDispatcher\BeforeDispatchEvent;
21
use ICanBoogie\Routing\RouteDispatcher\DispatchEvent;
22
use ICanBoogie\Routing\Route\RescueEvent;
23
24
/**
25
 * Dispatch requests among the defined routes.
26
 *
27
 * If a route matching the request is found, the `$route` and `$decontextualized_path`
28
 * properties are added to the {@link Request} instance. `$route` holds the {@link Route} instance,
29
 * `$decontextualized_path` holds the decontextualized path. The path is decontextualized using
30
 * the {@link decontextualize()} function.
31
 *
32
 * @property-read RouteCollection $routes
33
 */
34
class RouteDispatcher implements Dispatcher
35
{
36
	use AccessorTrait;
37
38
	/**
39
	 * Route collection.
40
	 *
41
	 * @var RouteCollection
42
	 */
43
	protected $routes;
44
45
	protected function get_routes()
46
	{
47
		return $this->routes;
48
	}
49
50
	/**
51
	 * @param RouteCollection|null $routes
52
	 */
53
	public function __construct(RouteCollection $routes = null)
54
	{
55
		$this->routes = $routes;
56
	}
57
58
	/**
59
	 * @param Request $request
60
	 *
61
	 * @return Response|null
62
	 */
63
	public function __invoke(Request $request)
64
	{
65
		$captured = [];
66
		$normalized_path = $this->normalize_path($request->normalized_path);
67
		$route = $this->resolve_route($request, $normalized_path, $captured);
68
69
		if (!$route)
70
		{
71
			return null;
72
		}
73
74
		if ($route->location)
75
		{
76
			return new RedirectResponse(contextualize($route->location), Status::FOUND);
77
		}
78
79
		$this->alter_params($route, $request, $captured);
80
81
		$request->context->route = $route;
82
		$request->decontextualized_path = $normalized_path;
0 ignored issues
show
Bug introduced by
The property decontextualized_path does not seem to exist. Did you mean context?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
83
84
		return $this->dispatch($route, $request);
85
	}
86
87
	/**
88
	 * Normalizes request path.
89
	 *
90
	 * @param string $path
91
	 *
92
	 * @return string Decontextualized path with trimmed ending slash.
93
	 */
94
	protected function normalize_path($path)
95
	{
96
		$normalized_path = decontextualize($path);
97
98
		if ($normalized_path != '/')
99
		{
100
			$normalized_path = rtrim($normalized_path, '/');
101
		}
102
103
		return $normalized_path;
104
	}
105
106
	/**
107
	 * Resolves route from request.
108
	 *
109
	 * @param Request $request
110
	 * @param string $normalized_path
111
	 * @param array $captured
112
	 *
113
	 * @return false|Route|null
114
	 */
115
	protected function resolve_route(Request $request, $normalized_path, array &$captured)
116
	{
117
		return $this->routes->find($normalized_path, $captured, $request->method);
118
	}
119
120
	/**
121
	 * Alters request parameters.
122
	 *
123
	 * @param Route $route
124
	 * @param Request $request
125
	 * @param array $captured Parameters captured from the request's path.
126
	 */
127
	protected function alter_params(Route $route, Request $request, array $captured)
0 ignored issues
show
Unused Code introduced by
The parameter $route is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
128
	{
129
		$request->path_params = $captured + $request->path_params;
130
		$request->params = $captured + $request->params;
131
	}
132
133
	/**
134
	 * Alters request context with route and controller.
135
	 *
136
	 * @param Request\Context $context
137
	 * @param Route $route
138
	 * @param callable $controller
139
	 */
140
	protected function alter_context(Request\Context $context, Route $route, callable $controller)
141
	{
142
		$context->route = $route;
143
		$context->controller = $controller;
144
	}
145
146
	/**
147
	 * Dispatches the route.
148
	 *
149
	 * @param Route $route
150
	 * @param Request $request
151
	 *
152
	 * @return Response|null
153
	 */
154
	protected function dispatch(Route $route, Request $request)
155
	{
156
		$response = null;
157
158
		new BeforeDispatchEvent($this, $route, $request, $response);
159
160
		if (!$response)
161
		{
162
			$response = $this->respond($route, $request);
163
		}
164
165
		new DispatchEvent($this, $route, $request, $response);
166
167
		return $response;
168
	}
169
170
	/**
171
	 * Returns a response for the route and request.
172
	 *
173
	 * If the controller's result is not `null` but is not in instance of {@link Response}, its
174
	 * result is wrapped in a {@link response} instance with the status code 200 and the
175
	 * `Content-Type` "text/html; charset=utf-8".
176
	 *
177
	 * @param Route $route
178
	 * @param Request $request
179
	 *
180
	 * @return Response|mixed
181
	 */
182
	protected function respond(Route $route, Request $request)
183
	{
184
		$controller = $this->resolve_controller($route->controller);
185
		$controller_args = [ $request ];
186
187
		$this->alter_context($request->context, $route, $controller);
188
189
		$response = $controller(...$controller_args);
190
191
		if ($response !== null && !$response instanceof Response)
192
		{
193
			$response = new Response($response, Status::OK, [
194
195
				'Content-Type' => 'text/html; charset=utf-8'
196
197
			]);
198
		}
199
200
		return $response;
201
	}
202
203
	/**
204
	 * Fires {@link \ICanBoogie\Routing\RouteDispatcher\RescueEvent} and returns the response provided
205
	 * by third parties. If no response was provided, the exception (or the exception provided by
206
	 * third parties) is re-thrown.
207
	 *
208
	 * @param \Exception $exception The exception to rescue.
209
	 * @param Request $request The request being dispatched.
210
	 *
211
	 * @throws \Exception if the exception cannot be rescued.
212
	 *
213
	 * @return Response
214
	 */
215
	public function rescue(\Exception $exception, Request $request)
216
	{
217
		if (isset($request->context->route))
218
		{
219
			$response = null;
220
221
			new RescueEvent($request->context->route, $exception, $request, $response);
222
223
			if ($response)
224
			{
225
				return $response;
226
			}
227
		}
228
229
		throw $exception;
230
	}
231
232
	/**
233
	 * @param callable|string $controller
234
	 *
235
	 * @return Controller
236
	 */
237
	protected function resolve_controller($controller)
238
	{
239
		if ($controller instanceof \Closure)
240
		{
241
			return new ClosureController($controller);
242
		}
243
244
		if (is_callable($controller))
245
		{
246
			return new ClosureController(function () use ($controller) {
247
248
				/* @var $this ClosureController */
249
250
				return $controller($this->request);
0 ignored issues
show
Documentation introduced by
The property request does not exist on object<ICanBoogie\Routing\RouteDispatcher>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
251
252
			});
253
		}
254
255
		return new $controller;
256
	}
257
}
258