Passed
Push — master ( ff0e62...6ed64e )
by Jean-Christophe
09:18
created

Router::getRouteInfoByName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.072

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 4
c 2
b 0
f 0
dl 0
loc 7
ccs 4
cts 5
cp 0.8
rs 10
cc 3
nc 3
nop 1
crap 3.072
1
<?php
2
3
namespace Ubiquity\controllers;
4
5
use Ubiquity\cache\CacheManager;
6
use Ubiquity\controllers\traits\RouterAdminTrait;
7
use Ubiquity\controllers\traits\RouterModifierTrait;
8
use Ubiquity\controllers\traits\RouterTestTrait;
9
use Ubiquity\log\Logger;
10
use Ubiquity\utils\http\URequest;
11
12
/**
13
 * Router manager.
14
 * Ubiquity\controllers$Router
15
 * This class is part of Ubiquity
16
 *
17
 * @author jcheron <[email protected]>
18
 * @version 1.0.13
19
 *
20
 */
21
class Router {
22
	use RouterModifierTrait,RouterAdminTrait,RouterTestTrait;
23
	protected static $routes;
24
25 9
	private static function cleanParam(string $param): string {
26 9
		if (\substr ( $param, - 1 ) === '/') {
27
			return \substr ( $param, 0, - 1 );
28
		}
29 9
		return $param;
30
	}
31
32 20
	private static function getRoute_(&$routeDetails, $routePath, $matches, $cachedResponse) {
33 20
		if (! isset ( $routeDetails ['controller'] )) {
34 11
			$method = \strtolower ( $_SERVER ['REQUEST_METHOD'] );
35 11
			if (isset ( $routeDetails [$method] )) {
36 11
				$routeDetailsMethod = $routeDetails [$method];
37 11
				return self::getRouteUrlParts ( [ 'path' => $routePath,'details' => $routeDetailsMethod ], $matches, $routeDetailsMethod ['cache'] ?? false, $routeDetailsMethod ['duration'] ?? null, $cachedResponse );
38
			}
39
		} else {
40 10
			return self::getRouteUrlParts ( [ 'path' => $routePath,'details' => $routeDetails ], $matches, $routeDetails ['cache'] ?? false, $routeDetails ['duration'] ?? null, $cachedResponse );
41
		}
42 10
		return false;
43
	}
44
45
	protected static function _getURL($routePath, $params) {
46
		$result = \preg_replace_callback ( '~\((.*?)\)~', function () use (&$params) {
47
			return \array_shift ( $params );
48
		}, $routePath );
49
		if (\sizeof ( $params ) > 0) {
50
			$result = \rtrim ( $result, '/' ) . '/' . \implode ( '/', $params );
51
		}
52
		return $result;
53
	}
54
55 1
	protected static function checkRouteName($routeDetails, $name) {
56 1
		if (! isset ( $routeDetails ['name'] )) {
57
			foreach ( $routeDetails as $methodRouteDetail ) {
58
				if (isset ( $methodRouteDetail ['name'] ) && $methodRouteDetail ['name'] == $name) {
59
					return true;
60
				}
61
			}
62
		}
63 1
		return isset ( $routeDetails ['name'] ) && $routeDetails ['name'] == $name;
64
	}
65
66 9
	protected static function setParamsInOrder(&$routeUrlParts, $paramsOrder, $params) {
67 9
		$index = 0;
68 9
		foreach ( $paramsOrder as $order ) {
69 9
			if ($order === '*') {
70
				if (isset ( $params [$index] )) {
71
					$routeUrlParts = \array_merge ( $routeUrlParts, \array_diff ( \explode ( '/', $params [$index] ), [ '' ] ) );
72
				}
73
				break;
74
			}
75 9
			if (($order [0] ?? '') === '~') {
76 5
				$order = \intval ( \substr ( $order, 1, 1 ) );
77 5
				if (isset ( $params [$order] )) {
78 5
					$routeUrlParts = \array_merge ( $routeUrlParts, \array_diff ( \explode ( '/', $params [$order] ), [ '' ] ) );
79 5
					break;
80
				}
81
			}
82 9
			$routeUrlParts [] = self::cleanParam ( $params [$order] );
83 9
			unset ( $params [$order] );
84 9
			$index ++;
85
		}
86 9
	}
87
88
	/**
89
	 * Starts the router by loading normal routes (not rest)
90
	 */
91 21
	public static function start(): void {
92 21
		self::$routes = CacheManager::getControllerCache ();
93 21
	}
94
95
	/**
96
	 * Starts the router by loading rest routes (not normal routes)
97
	 */
98 4
	public static function startRest(): void {
99 4
		self::$routes = CacheManager::getControllerCache ( true );
100 4
	}
101
102
	/**
103
	 * Starts the router by loading all routes (normal + rest routes)
104
	 */
105 36
	public static function startAll(): void {
106 36
		self::$routes = \array_merge ( CacheManager::getControllerCache (), CacheManager::getControllerCache ( true ) );
107 36
	}
108
109
	/**
110
	 * Returns the route corresponding to a path
111
	 *
112
	 * @param string $path The route path
113
	 * @param boolean $cachedResponse
114
	 * @return boolean|mixed[]|string
115
	 */
116 51
	public static function getRoute($path, $cachedResponse = true, $debug = false) {
117 51
		$path = self::slashPath ( $path );
118 51
		if (isset ( self::$routes [$path] ) && ! $debug) { // No direct access to route in debug mode (for maintenance mode activation)
119
			return self::getRoute_ ( self::$routes [$path], $path, [ $path ], $cachedResponse );
120
		}
121 51
		foreach ( self::$routes as $routePath => $routeDetails ) {
122 51
			if (\preg_match ( "@^{$routePath}\$@s", $path, $matches )) {
123 20
				if (($r = self::getRoute_ ( $routeDetails, $routePath, $matches, $cachedResponse )) !== false) {
124 20
					return $r;
125
				}
126
			}
127
		}
128 38
		return false;
129
	}
130
131
	/**
132
	 * Returns the generated path from a route
133
	 *
134
	 * @param string $name name of the route
135
	 * @param array $parameters array of the route parameters. default : []
136
	 * @param boolean $absolute
137
	 */
138
	public static function getRouteByName($name, $parameters = [ ], $absolute = true) {
139
		foreach ( self::$routes as $routePath => $routeDetails ) {
140
			if (self::checkRouteName ( $routeDetails, $name )) {
141
				if (\sizeof ( $parameters ) > 0) {
142
					$routePath = self::_getURL ( $routePath, $parameters );
143
				}
144
				if (trim ( $routePath, '/' ) == '_default') {
145
					$routePath = "/";
146
				}
147
				if (! $absolute) {
148
					return \ltrim ( $routePath, '/' );
149
				} else {
150
					return $routePath;
151
				}
152
			}
153
		}
154
		return false;
155
	}
156
157 1
	public static function getRouteInfoByName($name) {
158 1
		foreach ( self::$routes as $routeDetails ) {
159 1
			if (self::checkRouteName ( $routeDetails, $name )) {
160 1
				return $routeDetails;
161
			}
162
		}
163
		return false;
164
	}
165
166
	/**
167
	 * Returns the generated path from a route
168
	 *
169
	 * @param string $name The route name
170
	 * @param array $parameters default: []
171
	 * @param boolean $absolute true if the path is absolute (/ at first)
172
	 * @return boolean|string|array|mixed the generated path (/path/to/route)
173
	 */
174
	public static function path($name, $parameters = [ ], $absolute = false) {
175
		return self::getRouteByName ( $name, $parameters, $absolute );
176
	}
177
178
	/**
179
	 * Returns the generated url from a route
180
	 *
181
	 * @param string $name the route name
182
	 * @param array $parameters default: []
183
	 * @return string the generated url (http://myApp/path/to/route)
184
	 */
185
	public static function url($name, $parameters = [ ]): string {
186
		return URequest::getUrl ( self::getRouteByName ( $name, $parameters, false ) );
187
	}
188
189 20
	public static function getRouteUrlParts($routeArray, $params, $cached = false, $duration = NULL, $cachedResponse = true) {
190 20
		$realPath = \current ( $params );
191 20
		\array_shift ( $params );
192 20
		$routeDetails = $routeArray ['details'];
193 20
		if ($routeDetails ['controller'] instanceof \Closure) {
194
			$result = [ $routeDetails ['controller'] ];
195
			$resultStr = 'callable function';
196
		} else {
197 20
			$result = [ \str_replace ( "\\\\", "\\", $routeDetails ['controller'] ),$routeDetails ['action'] ];
198 20
			$resultStr = \implode ( '/', $result );
199
		}
200 20
		if (($paramsOrder = $routeDetails ['parameters']) && (\sizeof ( $paramsOrder ) > 0)) {
201 9
			self::setParamsInOrder ( $result, $paramsOrder, $params );
202
		}
203 20
		if (! $cached || ! $cachedResponse) {
204 20
			Logger::info ( 'Router', \sprintf ( 'Route found for %s : %s', $routeArray ['path'], $resultStr ), 'getRouteUrlParts' );
205 20
			if (isset ( $routeDetails ['callback'] )) {
206
				// Used for maintenance mode
207 1
				if ($routeDetails ['callback'] instanceof \Closure) {
208 1
					return $routeDetails ['callback'] ( $result );
209
				}
210
			}
211 19
			return $result;
212
		}
213
		Logger::info ( 'Router', sprintf ( 'Route found for %s (from cache) : %s', $realPath, $resultStr ), 'getRouteUrlParts' );
214
		return CacheManager::getRouteCache ( $realPath, $result, $duration );
215
	}
216
217
	/**
218
	 * Adds a slash before and after a path
219
	 *
220
	 * @param string $path The path to modify
221
	 * @return string The path with slashes
222
	 */
223 51
	public static function slashPath($path): string {
224 51
		if (\substr ( $path, 0, 1 ) !== '/') {
225 51
			$path = '/' . $path;
226
		}
227 51
		if (\substr ( $path, - 1 ) !== '/') {
228 43
			$path = $path . '/';
229
		}
230 51
		return $path;
231
	}
232
233
	/**
234
	 * Declare a route as expired
235
	 *
236
	 * @param string $routePath
237
	 */
238
	public static function setExpired($routePath): void {
239
		CacheManager::setExpired ( $routePath );
240
	}
241
242
	/**
243
	 * Returns the array of loaded routes
244
	 *
245
	 * @return array|mixed
246
	 */
247 51
	public static function getRoutes() {
248 51
		return self::$routes;
249
	}
250
}
251