Passed
Push — master ( ae5cc2...260dd0 )
by Jean-Christophe
08:29
created

Router   B

Complexity

Total Complexity 52

Size/Duplication

Total Lines 229
Duplicated Lines 0 %

Test Coverage

Coverage 73.39%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 52
eloc 94
c 4
b 0
f 0
dl 0
loc 229
ccs 80
cts 109
cp 0.7339
rs 7.44

17 Methods

Rating   Name   Duplication   Size   Complexity  
A getRoute_() 0 11 3
A cleanParam() 0 5 2
A checkRouteName() 0 9 6
A getRoute() 0 14 6
A startAll() 0 2 1
A setParamsInOrder() 0 19 6
A getRouteInfoByName() 0 7 3
A getRoutes() 0 2 1
B getRouteUrlParts() 0 26 8
A setExpired() 0 2 1
A start() 0 2 1
A path() 0 2 1
A _getURL() 0 8 2
A getRouteByName() 0 17 6
A slashPath() 0 8 3
A url() 0 2 1
A startRest() 0 2 1

How to fix   Complexity   

Complex Class

Complex classes like Router often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Router, and based on these observations, apply Extract Interface, too.

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.12
19
 *
20
 */
21
class Router {
22
	use RouterModifierTrait,RouterAdminTrait,RouterTestTrait;
23
	protected static $routes;
24
25 8
	private static function cleanParam(string $param): string {
26 8
		if (\substr ( $param, - 1 ) === '/') {
27
			return \substr ( $param, 0, - 1 );
28
		}
29 8
		return $param;
30
	}
31
32 19
	private static function getRoute_(&$routeDetails, $routePath, $matches, $cachedResponse) {
33 19
		if (! isset ( $routeDetails ['controller'] )) {
34 11
			$method = URequest::getMethod ();
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 9
			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 3
	protected static function checkRouteName($routeDetails, $name) {
56 3
		if (! isset ( $routeDetails ['name'] )) {
57 2
			foreach ( $routeDetails as $methodRouteDetail ) {
58 2
				if (isset ( $methodRouteDetail ['name'] ) && $methodRouteDetail ['name'] == $name) {
59
					return true;
60
				}
61
			}
62
		}
63 3
		return isset ( $routeDetails ['name'] ) && $routeDetails ['name'] == $name;
64
	}
65
66 8
	protected static function setParamsInOrder(&$routeUrlParts, $paramsOrder, $params) {
67 8
		$index = 0;
68 8
		foreach ( $paramsOrder as $order ) {
69 8
			if ($order === '*') {
70
				if (isset ( $params [$index] )) {
71
					$routeUrlParts = \array_merge ( $routeUrlParts, \array_diff ( \explode ( '/', $params [$index] ), [ '' ] ) );
72
				}
73
				break;
74
			}
75 8
			if (($order [0] ?? '') === '~') {
76 3
				$order = \intval ( \substr ( $order, 1, 1 ) );
77 3
				if (isset ( $params [$order] )) {
78 3
					$routeUrlParts = \array_merge ( $routeUrlParts, \array_diff ( \explode ( '/', $params [$order] ), [ '' ] ) );
79 3
					break;
80
				}
81
			}
82 8
			$routeUrlParts [] = self::cleanParam ( $params [$order] );
83 8
			unset ( $params [$order] );
84 8
			$index ++;
85
		}
86 8
	}
87
88
	/**
89
	 * Starts the router by loading normal routes (not rest)
90
	 */
91 18
	public static function start(): void {
92 18
		self::$routes = CacheManager::getControllerCache ();
93 18
	}
94
95
	/**
96
	 * Starts the router by loading rest routes (not normal routes)
97
	 */
98 2
	public static function startRest(): void {
99 2
		self::$routes = CacheManager::getControllerCache ( true );
100 2
	}
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 46
	public static function getRoute($path, $cachedResponse = true, $debug = false) {
117 46
		$path = self::slashPath ( $path );
118 46
		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 46
		foreach ( self::$routes as $routePath => $routeDetails ) {
122 46
			if (\preg_match ( "@^{$routePath}\$@s", $path, $matches )) {
123 19
				if (($r = self::getRoute_ ( $routeDetails, $routePath, $matches, $cachedResponse )) !== false) {
124 19
					return $r;
125
				}
126
			}
127
		}
128 34
		Logger::warn ( 'Router', "No route found for {$path}", 'getRoute' );
129 34
		return false;
130
	}
131
132
	/**
133
	 * Returns the generated path from a route
134
	 *
135
	 * @param string $name name of the route
136
	 * @param array $parameters array of the route parameters. default : []
137
	 * @param boolean $absolute
138
	 */
139 3
	public static function getRouteByName($name, $parameters = [ ], $absolute = true) {
140 3
		foreach ( self::$routes as $routePath => $routeDetails ) {
141 3
			if (self::checkRouteName ( $routeDetails, $name )) {
142 3
				if (\sizeof ( $parameters ) > 0) {
143
					$routePath = self::_getURL ( $routePath, $parameters );
144
				}
145 3
				if (trim ( $routePath, '/' ) == '_default') {
146 3
					$routePath = "/";
147
				}
148 3
				if (! $absolute) {
149 3
					return \ltrim ( $routePath, '/' );
150
				} else {
151
					return $routePath;
152
				}
153
			}
154
		}
155
		return false;
156
	}
157
158
	public static function getRouteInfoByName($name) {
159
		foreach ( self::$routes as $routeDetails ) {
160
			if (self::checkRouteName ( $routeDetails, $name )) {
161
				return $routeDetails;
162
			}
163
		}
164
		return false;
165
	}
166
167
	/**
168
	 * Returns the generated path from a route
169
	 *
170
	 * @param string $name The route name
171
	 * @param array $parameters default: []
172
	 * @param boolean $absolute true if the path is absolute (/ at first)
173
	 * @return boolean|string|array|mixed the generated path (/path/to/route)
174
	 */
175 3
	public static function path($name, $parameters = [ ], $absolute = false) {
176 3
		return self::getRouteByName ( $name, $parameters, $absolute );
177
	}
178
179
	/**
180
	 * Returns the generated url from a route
181
	 *
182
	 * @param string $name the route name
183
	 * @param array $parameters default: []
184
	 * @return string the generated url (http://myApp/path/to/route)
185
	 */
186
	public static function url($name, $parameters = [ ]): string {
187
		return URequest::getUrl ( self::getRouteByName ( $name, $parameters, false ) );
188
	}
189
190 19
	public static function getRouteUrlParts($routeArray, $params, $cached = false, $duration = NULL, $cachedResponse = true) {
191 19
		$realPath = \current ( $params );
192 19
		\array_shift ( $params );
193 19
		$routeDetails = $routeArray ['details'];
194 19
		if ($routeDetails ['controller'] instanceof \Closure) {
195
			$result = [ $routeDetails ['controller'] ];
196
			$resultStr = 'callable function';
197
		} else {
198 19
			$result = [ \str_replace ( "\\\\", "\\", $routeDetails ['controller'] ),$routeDetails ['action'] ];
199 19
			$resultStr = \implode ( '/', $result );
200
		}
201 19
		if (($paramsOrder = $routeDetails ['parameters']) && (\sizeof ( $paramsOrder ) > 0)) {
202 8
			self::setParamsInOrder ( $result, $paramsOrder, $params );
203
		}
204 19
		if (! $cached || ! $cachedResponse) {
205 19
			Logger::info ( 'Router', \sprintf ( 'Route found for %s : %s', $routeArray ['path'], $resultStr ), 'getRouteUrlParts' );
206 19
			if (isset ( $routeDetails ['callback'] )) {
207
				// Used for maintenance mode
208 1
				if ($routeDetails ['callback'] instanceof \Closure) {
209 1
					return $routeDetails ['callback'] ( $result );
210
				}
211
			}
212 18
			return $result;
213
		}
214
		Logger::info ( 'Router', sprintf ( 'Route found for %s (from cache) : %s', $realPath, $resultStr ), 'getRouteUrlParts' );
215
		return CacheManager::getRouteCache ( $realPath, $result, $duration );
216
	}
217
218
	/**
219
	 * Adds a slash before and after a path
220
	 *
221
	 * @param string $path The path to modify
222
	 * @return string The path with slashes
223
	 */
224 46
	public static function slashPath($path): string {
225 46
		if (\substr ( $path, 0, 1 ) !== '/') {
226 46
			$path = '/' . $path;
227
		}
228 46
		if (\substr ( $path, - 1 ) !== '/') {
229 38
			$path = $path . '/';
230
		}
231 46
		return $path;
232
	}
233
234
	/**
235
	 * Declare a route as expired
236
	 *
237
	 * @param string $routePath
238
	 */
239
	public static function setExpired($routePath): void {
240
		CacheManager::setExpired ( $routePath );
241
	}
242
243
	/**
244
	 * Returns the array of loaded routes
245
	 *
246
	 * @return array|mixed
247
	 */
248 46
	public static function getRoutes() {
249 46
		return self::$routes;
250
	}
251
}
252