Ubiquity 2.5.2
php rapid development framework
Loading...
Searching...
No Matches
Router.php
Go to the documentation of this file.
1<?php
2
4
12
23
24 protected static $routes;
25 protected static $statusCode;
26
27 private static function cleanParam(string $param): string {
28 if (\substr($param, -1) === '/') {
29 return \substr($param, 0, -1);
30 }
31 return $param;
32 }
33
34 private static function getRoute_(&$routeDetails, $routePath, $matches, $cachedResponse) {
35 self::$statusCode = RouterStatus::OK;
36 if (!isset ($routeDetails ['controller'])) {
37 $method = \strtolower($_SERVER ['REQUEST_METHOD']);
38 if (isset ($routeDetails [$method])) {
39 $routeDetailsMethod = $routeDetails [$method];
40 return self::getRouteUrlParts(['path' => $routePath, 'details' => $routeDetailsMethod], $matches, $routeDetailsMethod ['cache'] ?? false, $routeDetailsMethod ['duration'] ?? null, $cachedResponse);
41 }
42 self::$statusCode = RouterStatus::METHOD_NOT_ALLOWED;
43 } else {
44 return self::getRouteUrlParts(['path' => $routePath, 'details' => $routeDetails], $matches, $routeDetails ['cache'] ?? false, $routeDetails ['duration'] ?? null, $cachedResponse);
45 }
46 if (self::$statusCode === RouterStatus::OK) {
47 self::$statusCode = RouterStatus::NOT_FOUND;
48 }
49 return false;
50 }
51
52 protected static function _getURL($routePath, $params) {
53 $result = \preg_replace_callback('~\‍((.*?)\‍)~', function () use (&$params) {
54 return \array_shift($params);
55 }, $routePath);
56 if (\count($params) > 0) {
57 $result = \rtrim($result, '/') . '/' . \implode('/', $params);
58 }
59 return $result;
60 }
61
62 protected static function checkRouteName($routeDetails, $name) {
63 if (!isset ($routeDetails ['name'])) {
64 foreach ($routeDetails as $methodRouteDetail) {
65 if (isset ($methodRouteDetail ['name']) && $methodRouteDetail ['name'] == $name) {
66 return true;
67 }
68 }
69 }
70 return isset ($routeDetails ['name']) && $routeDetails ['name'] == $name;
71 }
72
73 protected static function setParamsInOrder($paramsOrder, $params) {
74 $index = 0;
75 $newParams = [];
76 foreach ($paramsOrder as $order) {
77 if ($order === '*') {
78 if (isset ($params [$index])) {
79 $newParams = \array_merge($newParams, \array_diff(\explode('/', $params [$index]), ['']));
80 }
81 break;
82 }
83 if (($order [0] ?? '') === '~') {
84 $order = \intval(\substr($order, 1, 1));
85 if (isset ($params [$order])) {
86 $newParams = \array_merge($newParams, \array_diff(\explode('/', $params [$order]), ['']));
87 break;
88 }
89 }
90 $newParams [] = self::cleanParam($params [$order]);
91 unset ($params [$order]);
92 $index++;
93 }
94 return $newParams;
95 }
96
100 public static function start(): void {
101 self::$routes = CacheManager::getControllerCache();
102 }
103
107 public static function startRest(): void {
108 self::$routes = CacheManager::getControllerCache(true);
109 }
110
114 public static function startAll(): void {
115 self::$routes = \array_merge(CacheManager::getControllerCache(), CacheManager::getControllerCache(true));
116 }
117
125 public static function getRoute($path, $cachedResponse = true, $debug = false) {
126 $path = self::slashPath($path);
127 if (isset (self::$routes [$path]) && !$debug) { // No direct access to route in debug mode (for maintenance mode activation)
128 return self::getRoute_(self::$routes [$path], $path, [$path], $cachedResponse);
129 }
130 foreach (self::$routes as $routePath => $routeDetails) {
131 if (\preg_match("@^{$routePath}\$@s", $path, $matches)) {
132 if (($r = self::getRoute_($routeDetails, $routePath, $matches, $cachedResponse)) !== false) {
133 return $r;
134 }
135 }
136 }
137 return false;
138 }
139
147 public static function getRouteByName($name, $parameters = [], $absolute = true) {
148 foreach (self::$routes as $routePath => $routeDetails) {
149 if (self::checkRouteName($routeDetails, $name)) {
150 if (\trim($routePath, '/') == '_default') {
151 return ($absolute) ? '/' : '';
152 }
153 if (\count($parameters) > 0) {
154 $routePath = self::_getURL($routePath, $parameters);
155 }
156 $routePath = \str_replace('//', '/', \preg_replace('~\‍((.*?)\‍)~', '', $routePath));
157 return ($absolute) ? $routePath : \ltrim($routePath, '/');
158 }
159 }
160 return false;
161 }
162
163 public static function getRouteInfoByName($name) {
164 foreach (self::$routes as $routeDetails) {
165 if (self::checkRouteName($routeDetails, $name)) {
166 return $routeDetails;
167 }
168 }
169 return false;
170 }
171
180 public static function path($name, $parameters = [], $absolute = false) {
181 return self::getRouteByName($name, $parameters, $absolute);
182 }
183
191 public static function url($name, $parameters = []): string {
192 return URequest::getUrl(self::getRouteByName($name, $parameters, false));
193 }
194
195 public static function getRouteUrlParts($routeArray, $params, $cached = false, $duration = null, $cachedResponse = true) {
196 $realPath = \current($params);
197 \array_shift($params);
198 $routeDetails = $routeArray ['details'];
199 if ($routeDetails ['controller'] instanceof \Closure) {
200 $result = ['callback' => $routeDetails ['controller']];
201 $resultStr = 'callable function';
202 } else {
203 $mainParams = null;
204 if (($mainMethodParams = $routeDetails['main.params'] ?? null) !== null) {
205 foreach ($mainMethodParams as $index => $mainMethodParam) {
206 $mainParams[$mainMethodParam] = $params[$index];
207 }
208 $params = \array_slice($params, $index + 1);
209 }
210 $result = ['controller' => \str_replace("\\\\", "\\", $routeDetails ['controller']), 'action' => $routeDetails ['action'], 'mainParams' => $mainParams];
211 $resultStr = \json_encode($result);
212 }
213 if (($paramsOrder = $routeDetails ['parameters']) && (\count($paramsOrder) > 0)) {
214 $result['params'] = self::setParamsInOrder($paramsOrder, $params);
215 }
216 if (!$cached || !$cachedResponse) {
217 Logger::info('Router', \sprintf('Route found for %s : %s', $routeArray ['path'], $resultStr), 'getRouteUrlParts');
218 if (isset ($routeDetails ['callback'])) {
219 // Used for maintenance mode
220 if ($routeDetails ['callback'] instanceof \Closure) {
221 return $routeDetails ['callback'] ($result);
222 }
223 }
224 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
236 public static function slashPath($path): string {
237 if (\substr($path, 0, 1) !== '/') {
238 $path = '/' . $path;
239 }
240 if (\substr($path, -1) !== '/') {
241 $path = $path . '/';
242 }
243 return $path;
244 }
245
251 public static function setExpired($routePath): void {
252 CacheManager::setExpired($routePath);
253 }
254
260 public static function getRoutes() {
261 return self::$routes;
262 }
263
269 public static function getStatusCode(): int {
270 return self::$statusCode;
271 }
272
278 public static function setStatusCode($statusCode): void {
279 self::$statusCode = $statusCode;
280 }
281}
Manager for caches (Router, Rest, models).
static setStatusCode($statusCode)
Set router response status code.
Definition Router.php:278
static start()
Starts the router by loading normal routes (not rest).
Definition Router.php:100
static _getURL($routePath, $params)
Definition Router.php:52
static slashPath($path)
Adds a slash before and after a path.
Definition Router.php:236
static getRoute($path, $cachedResponse=true, $debug=false)
Returns the route corresponding to a path.
Definition Router.php:125
static getRouteInfoByName($name)
Definition Router.php:163
static getRouteUrlParts($routeArray, $params, $cached=false, $duration=null, $cachedResponse=true)
Definition Router.php:195
static path($name, $parameters=[], $absolute=false)
Returns the generated path from a route.
Definition Router.php:180
static getRoutes()
Returns the array of loaded routes.
Definition Router.php:260
static getRouteByName($name, $parameters=[], $absolute=true)
Returns the generated path from a route.
Definition Router.php:147
static cleanParam(string $param)
Definition Router.php:27
static checkRouteName($routeDetails, $name)
Definition Router.php:62
static startAll()
Starts the router by loading all routes (normal + rest routes).
Definition Router.php:114
static url($name, $parameters=[])
Returns the generated url from a route.
Definition Router.php:191
static getStatusCode()
Return router response status code.
Definition Router.php:269
static setParamsInOrder($paramsOrder, $params)
Definition Router.php:73
static setExpired($routePath)
Declares a route as expired.
Definition Router.php:251
static startRest()
Starts the router by loading rest routes (not normal routes).
Definition Router.php:107
static getRoute_(&$routeDetails, $routePath, $matches, $cachedResponse)
Definition Router.php:34
Ubiquity\controllers\router$RouterStatus This class is part of Ubiquity.
Ubiquity\controllers\traits$RouterModifierTrait This class is part of Ubiquity.
Abstract class for logging Ubiquity\log$Logger This class is part of Ubiquity.
Definition Logger.php:14
Http Request utilities, wrapper for accessing to $_GET, $_POST and php://input.
Definition URequest.php:18