Passed
Push — master ( b9a8c8...31c054 )
by Jean-Christophe
12:35
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 2
Bugs 0 Features 0
Metric Value
eloc 1
c 2
b 0
f 0
dl 0
loc 2
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 3
crap 1
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 13
	private static function cleanParam(string $param): string {
26 13
		if (\substr ( $param, - 1 ) === '/') {
27
			return \substr ( $param, 0, - 1 );
28
		}
29 13
		return $param;
30
	}
31
32 32
	private static function getRoute_(&$routeDetails, $routePath, $matches, $cachedResponse) {
33 32
		if (! isset ( $routeDetails ['controller'] )) {
34 12
			$method = \strtolower ( $_SERVER ['REQUEST_METHOD'] );
35 12
			if (isset ( $routeDetails [$method] )) {
36 12
				$routeDetailsMethod = $routeDetails [$method];
37 12
				return self::getRouteUrlParts ( [ 'path' => $routePath,'details' => $routeDetailsMethod ], $matches, $routeDetailsMethod ['cache'] ?? false, $routeDetailsMethod ['duration'] ?? null, $cachedResponse );
38
			}
39
		} else {
40 21
			return self::getRouteUrlParts ( [ 'path' => $routePath,'details' => $routeDetails ], $matches, $routeDetails ['cache'] ?? false, $routeDetails ['duration'] ?? null, $cachedResponse );
41
		}
42 11
		return false;
43
	}
44
45 2
	protected static function _getURL($routePath, $params) {
46
		$result = \preg_replace_callback ( '~\((.*?)\)~', function () use (&$params) {
47 2
			return \array_shift ( $params );
48 2
		}, $routePath );
49 2
		if (\sizeof ( $params ) > 0) {
50
			$result = \rtrim ( $result, '/' ) . '/' . \implode ( '/', $params );
51
		}
52 2
		return $result;
53
	}
54
55 5
	protected static function checkRouteName($routeDetails, $name) {
56 5
		if (! isset ( $routeDetails ['name'] )) {
57 4
			foreach ( $routeDetails as $methodRouteDetail ) {
58 4
				if (isset ( $methodRouteDetail ['name'] ) && $methodRouteDetail ['name'] == $name) {
59
					return true;
60
				}
61
			}
62
		}
63 5
		return isset ( $routeDetails ['name'] ) && $routeDetails ['name'] == $name;
64
	}
65
66 16
	protected static function setParamsInOrder(&$routeUrlParts, $paramsOrder, $params) {
67 16
		$index = 0;
68 16
		foreach ( $paramsOrder as $order ) {
69 16
			if ($order === '*') {
70 1
				if (isset ( $params [$index] )) {
71 1
					$routeUrlParts = \array_merge ( $routeUrlParts, \array_diff ( \explode ( '/', $params [$index] ), [ '' ] ) );
72
				}
73 1
				break;
74
			}
75 15
			if (($order [0] ?? '') === '~') {
76 8
				$order = \intval ( \substr ( $order, 1, 1 ) );
77 8
				if (isset ( $params [$order] )) {
78 8
					$routeUrlParts = \array_merge ( $routeUrlParts, \array_diff ( \explode ( '/', $params [$order] ), [ '' ] ) );
79 8
					break;
80
				}
81
			}
82 13
			$routeUrlParts [] = self::cleanParam ( $params [$order] );
83 13
			unset ( $params [$order] );
84 13
			$index ++;
85
		}
86 16
	}
87
88
	/**
89
	 * Starts the router by loading normal routes (not rest)
90
	 */
91 43
	public static function start(): void {
92 43
		self::$routes = CacheManager::getControllerCache ();
93 43
	}
94
95
	/**
96
	 * Starts the router by loading rest routes (not normal routes)
97
	 */
98 5
	public static function startRest(): void {
99 5
		self::$routes = CacheManager::getControllerCache ( true );
100 5
	}
101
102
	/**
103
	 * Starts the router by loading all routes (normal + rest routes)
104
	 */
105 54
	public static function startAll(): void {
106 54
		self::$routes = \array_merge ( CacheManager::getControllerCache (), CacheManager::getControllerCache ( true ) );
107 54
	}
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 67
	public static function getRoute($path, $cachedResponse = true, $debug = false) {
117 67
		$path = self::slashPath ( $path );
118 67
		if (isset ( self::$routes [$path] ) && ! $debug) { // No direct access to route in debug mode (for maintenance mode activation)
119 5
			return self::getRoute_ ( self::$routes [$path], $path, [ $path ], $cachedResponse );
120
		}
121 66
		foreach ( self::$routes as $routePath => $routeDetails ) {
122 66
			if (\preg_match ( "@^{$routePath}\$@s", $path, $matches )) {
123 29
				if (($r = self::getRoute_ ( $routeDetails, $routePath, $matches, $cachedResponse )) !== false) {
124 29
					return $r;
125
				}
126
			}
127
		}
128 45
		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 3
	public static function getRouteByName($name, $parameters = [ ], $absolute = true) {
139 3
		foreach ( self::$routes as $routePath => $routeDetails ) {
140 3
			if (self::checkRouteName ( $routeDetails, $name )) {
141 3
				if (\sizeof ( $parameters ) > 0) {
142 2
					$routePath = self::_getURL ( $routePath, $parameters );
143
				}
144 3
				if (trim ( $routePath, '/' ) == '_default') {
145
					$routePath = "/";
146
				}
147 3
				if (! $absolute) {
148 2
					return \ltrim ( $routePath, '/' );
149
				} else {
150 2
					return $routePath;
151
				}
152
			}
153
		}
154 3
		return false;
155
	}
156
157 2
	public static function getRouteInfoByName($name) {
158 2
		foreach ( self::$routes as $routeDetails ) {
159 2
			if (self::checkRouteName ( $routeDetails, $name )) {
160 2
				return $routeDetails;
161
			}
162
		}
163 1
		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 1
	public static function path($name, $parameters = [ ], $absolute = false) {
175 1
		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 1
	public static function url($name, $parameters = [ ]): string {
186 1
		return URequest::getUrl ( self::getRouteByName ( $name, $parameters, false ) );
187
	}
188
189 32
	public static function getRouteUrlParts($routeArray, $params, $cached = false, $duration = NULL, $cachedResponse = true) {
190 32
		$realPath = \current ( $params );
191 32
		\array_shift ( $params );
192 32
		$routeDetails = $routeArray ['details'];
193 32
		if ($routeDetails ['controller'] instanceof \Closure) {
194 1
			$result = [ $routeDetails ['controller'] ];
195 1
			$resultStr = 'callable function';
196
		} else {
197 31
			$result = [ \str_replace ( "\\\\", "\\", $routeDetails ['controller'] ),$routeDetails ['action'] ];
198 31
			$resultStr = \implode ( '/', $result );
199
		}
200 32
		if (($paramsOrder = $routeDetails ['parameters']) && (\sizeof ( $paramsOrder ) > 0)) {
201 16
			self::setParamsInOrder ( $result, $paramsOrder, $params );
202
		}
203 32
		if (! $cached || ! $cachedResponse) {
204 32
			Logger::info ( 'Router', \sprintf ( 'Route found for %s : %s', $routeArray ['path'], $resultStr ), 'getRouteUrlParts' );
205 32
			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 31
			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 70
	public static function slashPath($path): string {
224 70
		if (\substr ( $path, 0, 1 ) !== '/') {
225 68
			$path = '/' . $path;
226
		}
227 70
		if (\substr ( $path, - 1 ) !== '/') {
228 59
			$path = $path . '/';
229
		}
230 70
		return $path;
231
	}
232
233
	/**
234
	 * Declare a route as expired
235
	 *
236
	 * @param string $routePath
237
	 */
238 1
	public static function setExpired($routePath): void {
239 1
		CacheManager::setExpired ( $routePath );
240 1
	}
241
242
	/**
243
	 * Returns the array of loaded routes
244
	 *
245
	 * @return array|mixed
246
	 */
247 67
	public static function getRoutes() {
248 67
		return self::$routes;
249
	}
250
}
251