Completed
Push — master ( 1f65a3...0feaa6 )
by Jean-Christophe
01:28
created

Router::getRouteUrlParts()   C

Complexity

Conditions 8
Paths 8

Size

Total Lines 28
Code Lines 22

Duplication

Lines 9
Ratio 32.14 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 9
loc 28
rs 5.3846
cc 8
eloc 22
nc 8
nop 5
1
<?php
2
3
namespace micro\controllers;
4
5
use micro\cache\CacheManager;
6
use micro\utils\RequestUtils;
7
use micro\cache\parser\ControllerParser;
8
use micro\utils\StrUtils;
9
10
/**
11
 * Router
12
 * @author jc
13
 * @version 1.0.0.2
14
 */
15
class Router {
16
	private static $routes;
17
18
	public static function slashPath($path){
19
		if(StrUtils::startswith($path,"/")===false)
20
			$path="/" . $path;
21
		if(!StrUtils::endswith($path, "/"))
22
			$path=$path."/";
23
		return $path;
24
	}
25
26
	public static function start() {
27
		self::$routes=CacheManager::getControllerCache();
28
	}
29
30
	public static function getRoute($path,$cachedResponse=true) {
31
		$path=self::slashPath($path);
32
		foreach ( self::$routes as $routePath => $routeDetails ) {
33
			if (preg_match("@^" . $routePath . "$@s", $path, $matches)) {
34
				if (!isset($routeDetails["controller"])) {
35
					$method=RequestUtils::getMethod();
36
					if (isset($routeDetails[$method]))
37
						return self::getRouteUrlParts([ "path" => $routePath,"details" => $routeDetails[$method] ], $matches, $routeDetails[$method]["cache"], $routeDetails[$method]["duration"],$cachedResponse);
38
				} else
39
					return self::getRouteUrlParts([ "path" => $routePath,"details" => $routeDetails ], $matches, $routeDetails["cache"], $routeDetails["duration"],$cachedResponse);
40
			}
41
		}
42
		return false;
43
	}
44
45
	public static function filterRoutes($path) {
46
		$path=self::slashPath($path);
47
		$result=[];
48
		foreach ( self::$routes as $routePath => $routeDetails ) {
49
			if (preg_match("@^" . $routePath . ".*?$@s", $path, $matches)) {
50
				$result[$routePath]=$routeDetails;
51
			}
52
		}
53
		return $result;
54
	}
55
56
	public static function getRouteInfo($path){
57
		$path=self::slashPath($path);
58
		foreach ( self::$routes as $routePath => $routeDetails ) {
59
			if (preg_match("@^" . $routePath . "$@s", $path, $matches)) {
60
				if (!isset($routeDetails["controller"])) {
61
						return \reset($routeDetails);
62
				} else
63
					return $routeDetails;
64
			}
65
		}
66
		return false;
67
	}
68
69
	public static function getAnnotations($controllerName,$actionName){
70
		$result=[];
71
		foreach ( self::$routes as $routePath => $routeDetails ) {
72
			if (!isset($routeDetails["controller"])) {
73
				$routeDetails=\reset($routeDetails);
74
			}
75
			if($routeDetails["controller"]===$controllerName && $routeDetails["action"]===$actionName)
76
				$result[$routePath]=$routeDetails;
77
		}
78
		return $result;
79
	}
80
81
	/**
82
	 * Retourne le chemin d'une route par son nom
83
	 * @param string $name nom de la route
84
	 */
85
	public static function getRouteByName($name, $absolute=true) {
86
		foreach ( self::$routes as $routePath => $routeDetails ) {
87
			if ($routeDetails["name"] == $name) {
88
				if ($absolute)
89
					return RequestUtils::getUrl($routePath);
90
				else
91
					return $routePath;
92
			}
93
		}
94
		return false;
95
	}
96
97
	public static function getRouteUrlParts($routeArray, $params, $cached=false, $duration=NULL,$cachedResponse=true) {
98
		$params=\array_slice($params, 1);
99
		$ctrl=str_replace("\\\\", "\\", $routeArray["details"]["controller"]);
100
		$result=[ $ctrl,$routeArray["details"]["action"] ];
101
		$paramsOrder=$routeArray["details"]["parameters"];
102
		$index=0;
103
		foreach ( $paramsOrder as $order ) {
104 View Code Duplication
			if($order==="*"){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
				if(isset($params[$index]))
106
					$result=\array_merge($result,\array_diff(\explode("/", $params[$index]),[""]));
107
				break;
108
			}
109
			if(\substr($order, 0,1)==="~"){
110
				$order=\intval(\substr($order,1,1));
111 View Code Duplication
				if(isset($params[$order])){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
112
					$result=\array_merge($result,\array_diff(\explode("/", $params[$order]),[""]));
113
					break;
114
				}
115
			}
116
			$result[]=self::cleanParam($params[$order]);
117
			unset($params[$order]);
118
			$index++;
119
		}
120
		if ($cached === true && $cachedResponse===true) {
121
			return CacheManager::getRouteCache($result, $duration);
122
		}
123
		return $result;
124
	}
125
126
	private static function cleanParam($param){
127
		if(StrUtils::endswith($param, "/"))
128
			return \substr($param, 0,-1);
129
		return $param;
130
	}
131
132
	/**
133
	 * Déclare une route comme étant expirée ou non
134
	 * @param string $routePath
135
	 * @param boolean $expired
136
	 */
137
	public static function setExpired($routePath, $expired=true) {
138
		CacheManager::setExpired($routePath, $expired);
139
	}
140
141
	/**
142
	 *
143
	 * @param string $path
144
	 * @param string $controller
145
	 * @param string $action
146
	 * @param array|null $methods
147
	 * @param string $name
148
	 * @param boolean $cache
149
	 * @param int $duration
150
	 */
151
	public static function addRoute($path, $controller, $action="index", $methods=null, $name="", $cache=false, $duration=null) {
152
		self::addRouteToRoutes(self::$routes, $path, $controller, $action, $methods, $name, $cache, $duration);
153
	}
154
155
	public static function addRouteToRoutes(&$routesArray, $path, $controller, $action="index", $methods=null, $name="", $cache=false, $duration=null) {
156
		$result=[ ];
157
		$method=new \ReflectionMethod($controller, $action);
158
		ControllerParser::parseRouteArray($result, $controller, [ "path" => $path,"methods" => $methods,"name" => $name,"cache" => $cache,"duration" => $duration ], $method, $action);
159
		foreach ( $result as $k => $v ) {
160
			$routesArray[$k]=$v;
161
		}
162
	}
163
}
164