RouteDispatcher   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 208
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 4
Bugs 0 Features 1
Metric Value
wmc 20
c 4
b 0
f 1
lcom 1
cbo 9
dl 0
loc 208
rs 10

10 Methods

Rating   Name   Duplication   Size   Complexity  
A get_routes() 0 4 1
A __construct() 0 4 1
A resolve_route() 0 4 1
A __invoke() 0 23 3
A normalize_path() 0 11 2
A alter_params() 0 5 1
A alter_context() 0 5 1
A dispatch() 0 15 2
B respond() 0 30 5
A rescue() 0 16 3
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 = $route->controller;
185
		$controller_args = [ $request ];
186
187
		if (!is_callable($controller))
188
		{
189
			$controller = new $controller;
190
		}
191
192
		if (!$controller instanceof Controller)
193
		{
194
			$controller_args = array_merge($controller_args, array_values($request->path_params));
195
		}
196
197
		$this->alter_context($request->context, $route, $controller);
198
199
		$response = call_user_func_array($controller, $controller_args);
200
201
		if ($response !== null && !$response instanceof Response)
202
		{
203
			$response = new Response($response, Status::OK, [
204
205
				'Content-Type' => 'text/html; charset=utf-8'
206
207
			]);
208
		}
209
210
		return $response;
211
	}
212
213
	/**
214
	 * Fires {@link \ICanBoogie\Routing\RouteDispatcher\RescueEvent} and returns the response provided
215
	 * by third parties. If no response was provided, the exception (or the exception provided by
216
	 * third parties) is re-thrown.
217
	 *
218
	 * @param \Exception $exception The exception to rescue.
219
	 * @param Request $request The request being dispatched.
220
	 *
221
	 * @throws \Exception if the exception cannot be rescued.
222
	 *
223
	 * @return Response
224
	 */
225
	public function rescue(\Exception $exception, Request $request)
226
	{
227
		if (isset($request->context->route))
228
		{
229
			$response = null;
230
231
			new RescueEvent($request->context->route, $exception, $request, $response);
232
233
			if ($response)
234
			{
235
				return $response;
236
			}
237
		}
238
239
		throw $exception;
240
	}
241
}
242