Passed
Push — master ( 685651...ff2960 )
by Atanas
02:52
created

Router::addGroupToStack()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 13
nc 2
nop 1
dl 0
loc 21
ccs 0
cts 17
cp 0
crap 6
rs 9.8333
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\HasUrlWhereInterface;
19
use WPEmerge\Routing\Conditions\InvalidRouteConditionException;
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
	 * Get the current route.
161
	 *
162
	 * @return RouteInterface
163
	 */
164 1
	public function getCurrentRoute() {
165 1
		return $this->current_route;
166
	}
167
168
	/**
169
	 * Set the current route.
170
	 *
171
	 * @param  RouteInterface
172
	 * @return void
173
	 */
174 1
	public function setCurrentRoute( RouteInterface $current_route ) {
175 1
		$this->current_route = $current_route;
176 1
	}
177
178
	/**
179
	 * Add a group to the group stack, mergin all previous attributes.
180
	 *
181
	 * @param array<string, mixed> $attributes
182
	 * @return void
183
	 */
184
	protected function addGroupToStack( $attributes ) {
185
		$previous = Arr::last( $this->group_stack, null, [] );
186
187
		$condition = $this->condition_factory->merge(
188
			Arr::get( $previous, 'condition', '' ),
189
			Arr::get( $attributes, 'condition', '' )
190
		);
191
192
		$attributes = array(
193
			'condition' => $condition !== null ? $condition : '',
194
			'where' => array_merge(
195
				Arr::get( $previous, 'where', [] ),
196
				Arr::get( $attributes, 'where', [] )
197
			),
198
			'middleware' => array_merge(
199
				(array) Arr::get( $previous, 'middleware', [] ),
200
				(array) Arr::get( $attributes, 'middleware', [] )
201
			),
202
		);
203
204
		$this->group_stack[] = $attributes;
205
	}
206
207
	/**
208
	 * Remove last group from the group stack.
209
	 *
210
	 * @return void
211
	 */
212
	protected function removeLastGroupFromStack() {
213
		array_pop( $this->group_stack );
214
	}
215
216
	/**
217
	 * Create a new route group.
218
	 *
219
	 * @param array<string, mixed> $attributes
220
	 * @param \Closure            $routes
221
	 * @return void
222
	 */
223 1
	public function group( $attributes, $routes ) {
224 1
		$this->addGroupToStack( $attributes );
225
226 1
		$routes();
227
228 1
		$this->removeLastGroupFromStack();
229 1
	}
230
231
	/**
232
	 * {@inheritDoc}
233
	 */
234
	public function makeRoute( $methods, $condition, $handler ) {
235
		if ( ! $condition instanceof ConditionInterface ) {
236
			try {
237
				$condition = $this->condition_factory->make( $condition );
238
			} catch ( InvalidRouteConditionException $e ) {
239
				throw new InvalidRouteConditionException( 'Route condition is not a valid route string or condition.' );
240
			}
241
		}
242
243
		return new Route( $methods, $condition, $handler );
244
	}
245
246
	/**
247
	 * {@inheritDoc}
248
	 */
249 2
	public function addRoute( $route ) {
250 2
		$group = Arr::last( $this->group_stack, null, [] );
251 2
		$condition = $route->getCondition();
252
253 2
		if ( $condition instanceof HasUrlWhereInterface ) {
254
			$condition->setUrlWhere( array_merge(
255
				Arr::get( $group, 'where', [] ),
256
				$condition->getUrlWhere()
257
			) );
258
		}
259
260 2
		$condition = $this->condition_factory->merge(
261 2
			Arr::get( $group, 'condition', '' ),
262
			$condition
263 2
		);
264
265 2
		$route->setCondition( $condition );
266
267 2
		$route->setMiddleware( array_merge(
268 2
			$this->middleware,
269 2
			Arr::get( $group, 'middleware', [] ),
270 2
			$route->getMiddleware()
271 2
		) );
272
273 2
		return $this->traitAddRoute( $route );
274
	}
275
276
	/**
277
	 * Execute the first satisfied route, if any.
278
	 *
279
	 * @internal
280
	 * @param  string $view
281
	 * @return string
282
	 * @throws Exception
283
	 */
284 5
	public function execute( $view ) {
285 5
		$routes = $this->getRoutes();
286
287 5
		foreach ( $routes as $route ) {
288 5
			if ( $route->isSatisfied( $this->request ) ) {
289 4
				$this->setCurrentRoute( $route );
290 4
				return $this->handle( $this->request, $route, $view );
291
			}
292 1
		}
293
294 1
		return $view;
295
	}
296
297
	/**
298
	 * Execute a route.
299
	 *
300
	 * @throws Exception
301
	 * @param  RequestInterface $request
302
	 * @param  RouteInterface   $route
303
	 * @param  string           $view
304
	 * @return string
305
	 */
306 3
	protected function handle( RequestInterface $request, RouteInterface $route, $view ) {
307
		try {
308 3
			$this->error_handler->register();
309 3
			$response = $route->handle( $request, $view );
310 2
			$this->error_handler->unregister();
311 3
		} catch ( Exception $e ) {
312 1
			$response = $this->error_handler->getResponse( $e );
313
		}
314
315 2
		$container = Framework::getContainer();
316 2
		$container[ WPEMERGE_RESPONSE_KEY ] = $response;
317
318 2
		return WPEMERGE_DIR . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'view.php';
319
	}
320
321
	/**
322
	 * Handle ALL requests.
323
	 *
324
	 * @param  string|\Closure|null $handler
325
	 * @return RouteInterface
326
	 */
327 1
	public function handleAll( $handler = null ) {
328
		// match ANY request method
329
		// match ANY url
330
		// by default, use built-in WordPress controller
331 1
		return $this->any( '*', $handler );
332
	}
333
}
334