Passed
Push — master ( bd3cb9...127ddb )
by Jean-Christophe
17:45
created

Router::path()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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