Passed
Push — master ( b7467b...db04eb )
by Atanas
02:41
created

Router::handle()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 3
nop 3
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
ccs 0
cts 11
cp 0
crap 12
1
<?php
2
3
namespace Obsidian\Routing;
4
5
use Exception;
6
use Psr\Http\Message\ResponseInterface;
7
use Obsidian\Framework;
8
use Obsidian\Request;
9
use Obsidian\Response as FrameworkResponse;
10
11
/**
12
 * Provide routing
13
 */
14
class Router {
15
	use HasRoutesTrait;
16
17
	/**
18
	 * Hook into WordPress actions
19
	 *
20
	 * @return null
21
	 */
22
	public function boot() {
23
		add_action( 'init', array( $this, 'registerRewriteRules' ), 1000 );
24
		add_action( 'template_include', array( $this, 'execute' ), 1000 );
25
	}
26
27
	/**
28
	 * Register route rewrite rules with WordPress
29
	 *
30
	 * @return null
31
	 */
32
	public function registerRewriteRules() {
33
		$rules = apply_filters( 'obsidian_routing_rewrite_rules', [] );
34
		foreach ( $rules as $rule => $rewrite_to ) {
35
			add_rewrite_rule( $rule, $rewrite_to, 'top' );
36
		}
37
	}
38
39
	/**
40
	 * Add global middlewares and execute the first satisfied route (if any)
41
	 *
42
	 * @param  string $template
43
	 * @return string
44
	 */
45
	public function execute( $template ) {
46
		$routes = $this->getRoutes();
47
		$global_middleware = Framework::resolve( 'framework.routing.global_middleware' );
48
		$request = Request::fromGlobals();
49
50
		foreach ( $routes as $route ) {
51
			$route->addMiddleware( $global_middleware );
52
		}
53
54
		foreach ( $routes as $route ) {
55
			if ( $route->satisfied( $request ) ) {
56
				return $this->handle( $request, $route, $template );
57
			}
58
		}
59
60
		return $template;
61
	}
62
63
	/**
64
	 * Execute a route
65
	 *
66
	 * @param  Request        $request
67
	 * @param  RouteInterface $route
68
	 * @param  string         $template
69
	 * @return string
70
	 */
71
	protected function handle( Request $request, RouteInterface $route, $template ) {
72
		$response = $route->handle( $request, $template );
73
74
		if ( ! is_a( $response, ResponseInterface::class ) ) {
75
			if ( Framework::debugging() ) {
76
				throw new Exception( 'Response returned by controller is not valid (expectected ' . ResponseInterface::class . '; received ' . gettype( $response ) . ').' );
77
			}
78
			$response = FrameworkResponse::error( FrameworkResponse::response(), 500 );
79
		}
80
81
		add_filter( 'obsidian_response', function() use ( $response ) {
82
			return $response;
83
		} );
84
85
		return OBSIDIAN_DIR . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'template.php';
86
	}
87
}
88