Passed
Branch refactor/route-groups (411840)
by Atanas
01:44
created

Router::makeCondition()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 6
ccs 0
cts 4
cp 0
crap 6
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
			return $old->concatenateUrl( $new->getUrl() );
203
		}
204
205
		return $this->makeCondition( ['multiple', [$old, $new]] );
206
	}
207
208
	/**
209
	 * Merge group where attribute.
210
	 *
211
	 * @param array<string,string> $old
212
	 * @param array<string,string> $new
213
	 * @return array
214
	 */
215
	protected function mergeWhere( $old, $new ) {
216
		return array_merge( $old, $new );
217
	}
218
219
	/**
220
	 * Merge group middleware attribute.
221
	 *
222
	 * @param array $old
223
	 * @param array $new
224
	 * @return array
225
	 */
226
	protected function mergeMiddleware( $old, $new ) {
227
		return array_merge( $old, $new );
228
	}
229
230
	/**
231
	 * Add a group to the group stack, mergin all previous attributes.
232
	 *
233
	 * @param array<string,mixed> $attributes
234
	 * @return void
235
	 */
236
	protected function addGroupToStack( $attributes ) {
237
		$last_group = Arr::last( $this->group_stack, null, [] );
238
239
		$attributes = array(
240
			'condition' => $this->mergeCondition(
241
				Arr::get( $last_group, 'condition', '' ),
242
				Arr::get( $attributes, 'condition', '' )
243
			),
244
			'where' => $this->mergeWhere(
245
				Arr::get( $last_group, 'where', [] ),
246
				Arr::get( $attributes, 'where', [] )
247
			),
248
			'middleware' => $this->mergeMiddleware(
249
				(array) Arr::get( $last_group, 'middleware', [] ),
250
				(array) Arr::get( $attributes, 'middleware', [] )
251
			),
252
		);
253
254
		$this->group_stack[] = $attributes;
255
	}
256
257
	/**
258
	 * Remove last group from the group stack.
259
	 *
260
	 * @return void
261
	 */
262
	protected function removeLastGroupFromStack() {
263
		array_pop( $this->group_stack );
264
	}
265
266
	/**
267
	 * Create a new route group.
268
	 *
269
	 * @param array<string,mixed> $attributes
270
	 * @param \Closure            $routes
271
	 * @return void
272
	 */
273
	public function group( $attributes, $routes ) {
274
		$this->addGroupToStack( $attributes );
275
276
		$routes();
277
278
		$this->removeLastGroupFromStack();
279
	}
280
281
	/**
282
	 * {@inheritDoc}
283
	 */
284 2
	public function addRoute( $route ) {
285 2
		$group = Arr::last( $this->group_stack, null, [] );
286 2
		$condition = $route->getCondition();
287
288 2
		$condition = $this->mergeCondition(
289 2
			Arr::get( $group, 'condition', '' ),
290 2
			$condition
291
		);
292
293 2
		if ( $condition === '' ) {
294 2
			$condition = $this->makeCondition( $condition );
295
		}
296
297 2
		if ( $condition instanceof HasUrlInterface ) {
298 2
			$condition->setUrlWhere( $this->mergeWhere(
299 2
				Arr::get( $group, 'where', [] ),
300 2
				$condition->getUrlWhere()
301
			) );
302
		}
303
304 2
		$route->setCondition( $condition );
305
306 2
		$route->setMiddleware( $this->mergeMiddleware(
307 2
			array_merge(
308 2
				$this->middleware,
309 2
				Arr::get( $group, 'middleware', [] )
310
			),
311 2
			$route->getMiddleware()
312
		) );
313
314 2
		return $this->traitAddRoute( $route );
315
	}
316
317
	/**
318
	 * Execute the first satisfied route, if any.
319
	 *
320
	 * @internal
321
	 * @param  string $view
322
	 * @return string
323
	 * @throws Exception
324
	 */
325 5
	public function execute( $view ) {
326 5
		$routes = $this->getRoutes();
327
328 5
		foreach ( $routes as $route ) {
329 5
			if ( $route->isSatisfied( $this->request ) ) {
330 4
				$this->setCurrentRoute( $route );
331 5
				return $this->handle( $this->request, $route, $view );
332
			}
333
		}
334
335 1
		return $view;
336
	}
337
338
	/**
339
	 * Execute a route.
340
	 *
341
	 * @throws Exception
342
	 * @param  RequestInterface $request
343
	 * @param  RouteInterface   $route
344
	 * @param  string           $view
345
	 * @return string
346
	 */
347 3
	protected function handle( RequestInterface $request, RouteInterface $route, $view ) {
348
		try {
349 3
			$this->error_handler->register();
350 3
			$response = $route->handle( $request, $view );
351 2
			$this->error_handler->unregister();
352 1
		} catch ( Exception $e ) {
353 1
			$response = $this->error_handler->getResponse( $e );
354
		}
355
356 2
		$container = Framework::getContainer();
357 2
		$container[ WPEMERGE_RESPONSE_KEY ] = $response;
358
359 2
		return WPEMERGE_DIR . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'view.php';
360
	}
361
362
	/**
363
	 * Get the current route.
364
	 *
365
	 * @return RouteInterface
366
	 */
367 1
	public function getCurrentRoute() {
368 1
		return $this->current_route;
369
	}
370
371
	/**
372
	 * Set the current route.
373
	 *
374
	 * @param  RouteInterface
375
	 * @return void
376
	 */
377 1
	public function setCurrentRoute( RouteInterface $current_route ) {
378 1
		$this->current_route = $current_route;
379 1
	}
380
381
	/**
382
	 * Handle ALL requests.
383
	 *
384
	 * @param  string|\Closure|null $handler
385
	 * @return RouteInterface
386
	 */
387 1
	public function handleAll( $handler = null ) {
388
		// match ANY request method
389
		// match ANY url
390
		// by default, use built-in WordPress controller
391 1
		return $this->any( '*', $handler );
392
	}
393
}
394