Passed
Branch refactor/route-groups (c18eda)
by Atanas
01:54
created

Router::mergeMiddleware()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 2
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @package   WPEmerge
4
 * @author    Atanas Angelov <[email protected]>
5
 * @copyright 2018 Atanas Angelov
6
 * @license   https://www.gnu.org/licenses/gpl-2.0.html GPL-2.0
7
 * @link      https://wpemerge.com/
8
 */
9
10
namespace WPEmerge\Routing;
11
12
use Exception;
13
use WPEmerge\Exceptions\ErrorHandlerInterface;
14
use WPEmerge\Facades\Framework;
15
use WPEmerge\Requests\RequestInterface;
16
use WPEmerge\Routing\Conditions\ConditionFactory;
17
use WPEmerge\Routing\Conditions\ConditionInterface;
18
use WPEmerge\Routing\Conditions\HasUrlInterface;
19
use WPEmerge\Routing\Conditions\UrlCondition;
20
use WPEmerge\Support\Arr;
21
22
/**
23
 * Provide routing for site requests (i.e. all non-api requests)
24
 */
25
class Router implements HasRoutesInterface {
26
	use HasRoutesTrait {
27
		addRoute as traitAddRoute;
28
	}
29
30
	/**
31
	 * Current request.
32
	 *
33
	 * @var RequestInterface
34
	 */
35
	protected $request = null;
36
37
	/**
38
	 * Condition factory.
39
	 *
40
	 * @var ConditionFactory
41
	 */
42
	protected $condition_factory = null;
43
44
	/**
45
	 * Global middleware.
46
	 *
47
	 * @var array
48
	 */
49
	protected $middleware = [];
50
51
	/**
52
	 * Global middleware priority.
53
	 *
54
	 * @var array
55
	 */
56
	protected $middleware_priority = [];
57
58
	/**
59
	 * Default global middleware priority.
60
	 *
61
	 * @var integer
62
	 */
63
	protected $default_middleware_priority = 0;
64
65
	/**
66
	 * Exception handler.
67
	 *
68
	 * @var ErrorHandlerInterface
69
	 */
70
	protected $error_handler = null;
71
72
	/**
73
	 * Current active route.
74
	 *
75
	 * @var RouteInterface
76
	 */
77
	protected $current_route = null;
78
79
	/**
80
	 * Group stack.
81
	 *
82
	 * @var array<array<string,mixed>>
83
	 */
84
	protected $group_stack = [];
85
86
	/**
87
	 * Constructor.
88
	 *
89
	 * @codeCoverageIgnore
90
	 *
91
	 * @param RequestInterface      $request
92
	 * @param ConditionFactory      $condition_factory
93
	 * @param array                 $middleware
94
	 * @param array                 $middleware_priority
95
	 * @param integer               $default_middleware_priority
96
	 * @param ErrorHandlerInterface $error_handler
97
	 */
98
	public function __construct(
99
		RequestInterface $request,
100
		ConditionFactory $condition_factory,
101
		$middleware,
102
		$middleware_priority,
103
		$default_middleware_priority,
104
		ErrorHandlerInterface $error_handler
105
	) {
106
		$this->request = $request;
107
		$this->condition_factory = $condition_factory;
108
		$this->middleware_priority = $middleware_priority;
109
		$this->default_middleware_priority = $default_middleware_priority;
110
		$this->middleware = $this->sortMiddleware( $middleware );
111
		$this->error_handler = $error_handler;
112
	}
113
114
	/**
115
	 * Hook into WordPress actions.
116
	 *
117
	 * @codeCoverageIgnore
118
	 * @return void
119
	 */
120
	public function boot() {
121
		add_action( 'template_include', [$this, 'execute'], 1000 );
122
	}
123
124
	/**
125
	 * Get middleware priority.
126
	 *
127
	 * @param  mixed   $middleware
128
	 * @return integer
129
	 */
130 1
	public function getMiddlewarePriority( $middleware ) {
131 1
		if ( is_string( $middleware ) && isset( $this->middleware_priority[ $middleware ] ) ) {
132 1
			return $this->middleware_priority[ $middleware ];
133
		}
134
135 1
		return $this->default_middleware_priority;
136
	}
137
138
	/**
139
	 * Sort middleware by priority in ascending order.
140
	 *
141
	 * @param  array $middleware
142
	 * @return array
143
	 */
144
	public function sortMiddleware( $middleware ) {
145 1
		usort( $middleware, function ( $a, $b ) use ( $middleware ) {
146 1
			$priority = $this->getMiddlewarePriority( $a ) - $this->getMiddlewarePriority( $b );
147
148 1
			if ( $priority !== 0 ) {
149 1
				return $priority;
150
			}
151
152
			// Keep original array order.
153 1
			return array_search( $a, $middleware ) - array_search( $b, $middleware );
154 1
		} );
155
156 1
		return array_values( $middleware );
157
	}
158
159
	/**
160
	 * Create a condition.
161
	 *
162
	 * @param  string|array|ConditionInterface $condition
163
	 * @return ConditionInterface
164
	 */
165
	protected function makeCondition( $condition ) {
166
		if ( $condition instanceof ConditionInterface ) {
167
			return $condition;
168
		}
169
170
		return $this->condition_factory->make( $condition );
171
	}
172
173
	/**
174
	 * Merge group condition attribute.
175
	 *
176
	 * @param  string|array|ConditionInterface $old
177
	 * @param  string|array|ConditionInterface $new
178
	 * @return ConditionInterface|string
179
	 */
180
	protected function mergeCondition( $old, $new ) {
181
		if ( empty( $old ) ) {
182
			if ( empty( $new ) ) {
183
				return '';
184
			}
185
			return $this->makeCondition( $new );
186
		} else if ( empty( $new ) ) {
187
			return $this->makeCondition( $old );
188
		}
189
190
		return $this->mergeConditionInstances( $this->makeCondition( $old ), $this->makeCondition( $new ) );
191
	}
192
193
	/**
194
	 * Merge condition instances.
195
	 *
196
	 * @param  ConditionInterface $old
197
	 * @param  ConditionInterface $new
198
	 * @return ConditionInterface
199
	 */
200
	protected function mergeConditionInstances( ConditionInterface $old, ConditionInterface $new ) {
201
		if ( $old instanceof UrlCondition && $new instanceof UrlCondition ) {
202
			$concatenated = $old->concatenateUrl( $new->getUrl() );
203
204
			$concatenated->setUrlWhere( array_merge(
205
				$old->getUrlWhere(),
206
				$new->getUrlWhere()
207
			) );
208
209
			return $concatenated;
210
		}
211
212
		return $this->makeCondition( ['multiple', [$old, $new]] );
213
	}
214
215
	/**
216
	 * Merge group where attribute.
217
	 *
218
	 * @param array<string,string> $old
219
	 * @param array<string,string> $new
220
	 * @return array
221
	 */
222
	protected function mergeWhere( $old, $new ) {
223
		return array_merge( $old, $new );
224
	}
225
226
	/**
227
	 * Merge group middleware attribute.
228
	 *
229
	 * @param array $old
230
	 * @param array $new
231
	 * @return array
232
	 */
233
	protected function mergeMiddleware( $old, $new ) {
234
		return array_merge( $old, $new );
235
	}
236
237
	/**
238
	 * Add a group to the group stack, mergin all previous attributes.
239
	 *
240
	 * @param array<string,mixed> $attributes
241
	 * @return void
242
	 */
243
	protected function addGroupToStack( $attributes ) {
244
		$last_group = Arr::last( $this->group_stack, null, [] );
245
246
		$attributes = array(
247
			'condition' => $this->mergeCondition(
248
				Arr::get( $last_group, 'condition', '' ),
249
				Arr::get( $attributes, 'condition', '' )
250
			),
251
			'where' => $this->mergeWhere(
252
				Arr::get( $last_group, 'where', [] ),
253
				Arr::get( $attributes, 'where', [] )
254
			),
255
			'middleware' => $this->mergeMiddleware(
256
				(array) Arr::get( $last_group, 'middleware', [] ),
257
				(array) Arr::get( $attributes, 'middleware', [] )
258
			),
259
		);
260
261
		$this->group_stack[] = $attributes;
262
	}
263
264
	/**
265
	 * Remove last group from the group stack.
266
	 *
267
	 * @return void
268
	 */
269
	protected function removeLastGroupFromStack() {
270
		array_pop( $this->group_stack );
271
	}
272
273
	/**
274
	 * Create a new route group.
275
	 *
276
	 * @param array<string,mixed> $attributes
277
	 * @param \Closure            $routes
278
	 * @return void
279
	 */
280 1
	public function group( $attributes, $routes ) {
281 1
		$this->addGroupToStack( $attributes );
282
283 1
		$routes();
284
285 1
		$this->removeLastGroupFromStack();
286 1
	}
287
288
	/**
289
	 * {@inheritDoc}
290
	 */
291 2
	public function addRoute( $route ) {
292 2
		$group = Arr::last( $this->group_stack, null, [] );
293 2
		$condition = $route->getCondition();
294
295 2
		if ( $condition === '' ) {
296
			$condition = $this->makeCondition( $condition );
297
		}
298
299 2
		if ( $condition instanceof HasUrlInterface ) {
300
			$condition->setUrlWhere( $this->mergeWhere(
301
				Arr::get( $group, 'where', [] ),
302
				$condition->getUrlWhere()
303
			) );
304
		}
305
306 2
		$condition = $this->mergeCondition(
307 2
			Arr::get( $group, 'condition', '' ),
308 2
			$condition
309
		);
310
311 2
		$route->setCondition( $condition );
312
313 2
		$route->setMiddleware( $this->mergeMiddleware(
314 2
			array_merge(
315 2
				$this->middleware,
316 2
				Arr::get( $group, 'middleware', [] )
317
			),
318 2
			$route->getMiddleware()
319
		) );
320
321 2
		return $this->traitAddRoute( $route );
322
	}
323
324
	/**
325
	 * Execute the first satisfied route, if any.
326
	 *
327
	 * @internal
328
	 * @param  string $view
329
	 * @return string
330
	 * @throws Exception
331
	 */
332 5
	public function execute( $view ) {
333 5
		$routes = $this->getRoutes();
334
335 5
		foreach ( $routes as $route ) {
336 5
			if ( $route->isSatisfied( $this->request ) ) {
337 4
				$this->setCurrentRoute( $route );
338 5
				return $this->handle( $this->request, $route, $view );
339
			}
340
		}
341
342 1
		return $view;
343
	}
344
345
	/**
346
	 * Execute a route.
347
	 *
348
	 * @throws Exception
349
	 * @param  RequestInterface $request
350
	 * @param  RouteInterface   $route
351
	 * @param  string           $view
352
	 * @return string
353
	 */
354 3
	protected function handle( RequestInterface $request, RouteInterface $route, $view ) {
355
		try {
356 3
			$this->error_handler->register();
357 3
			$response = $route->handle( $request, $view );
358 2
			$this->error_handler->unregister();
359 1
		} catch ( Exception $e ) {
360 1
			$response = $this->error_handler->getResponse( $e );
361
		}
362
363 2
		$container = Framework::getContainer();
364 2
		$container[ WPEMERGE_RESPONSE_KEY ] = $response;
365
366 2
		return WPEMERGE_DIR . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'view.php';
367
	}
368
369
	/**
370
	 * Get the current route.
371
	 *
372
	 * @return RouteInterface
373
	 */
374 1
	public function getCurrentRoute() {
375 1
		return $this->current_route;
376
	}
377
378
	/**
379
	 * Set the current route.
380
	 *
381
	 * @param  RouteInterface
382
	 * @return void
383
	 */
384 1
	public function setCurrentRoute( RouteInterface $current_route ) {
385 1
		$this->current_route = $current_route;
386 1
	}
387
388
	/**
389
	 * Handle ALL requests.
390
	 *
391
	 * @param  string|\Closure|null $handler
392
	 * @return RouteInterface
393
	 */
394 1
	public function handleAll( $handler = null ) {
395
		// match ANY request method
396
		// match ANY url
397
		// by default, use built-in WordPress controller
398 1
		return $this->any( '*', $handler );
399
	}
400
}
401