Comus Party 1.0.0
Application web de mini-jeux en ligne
Chargement...
Recherche...
Aucune correspondance
Router.php
Aller à la documentation de ce fichier.
1<?php
9
10namespace ComusParty\App;
11
12use ComusParty\App\Exceptions\RouteNotFoundException;
13use ComusParty\App\Exceptions\UnauthorizedAccessException;
14use ComusParty\Controllers\ControllerFactory;
15use Exception;
16
22class Router
23{
28 private static ?Router $instance = null;
33 protected array $routes = [];
34
39 private function __construct()
40 {
41 }
42
47 public static function getInstance(): Router
48 {
49 if (is_null(self::$instance)) {
50 self::$instance = new Router();
51 }
52 return self::$instance;
53 }
54
62 public function get(string $url, callable $target, ?string $middleware = null): void
63 {
64 $this->addRoute('GET', $url, $target, $middleware);
65 }
66
75 private function addRoute(string $method, string $url, callable $target, ?string $middleware = null): void
76 {
77 if (is_null($middleware)) {
78 $middleware = '*';
79 }
80
81 $this->routes[$method][$middleware][BASE_URI . $url] = $target;
82 }
83
91 public function post(string $url, callable $target, ?string $middleware = null): void
92 {
93 $this->addRoute('POST', $url, $target, $middleware);
94 }
95
103 public function put(string $url, callable $target, ?string $middleware = null): void
104 {
105 $this->addRoute('PUT', $url, $target, $middleware);
106 }
107
115 public function delete(string $url, callable $target, ?string $middleware = null): void
116 {
117 $this->addRoute('DELETE', $url, $target, $middleware);
118 }
119
139 public function matchRoute(): void
140 {
141 $method = $_SERVER['REQUEST_METHOD'];
142 $url = $_SERVER['REQUEST_URI'];
143
144 if (is_null($_SESSION['uuid'] ?? null)) {
145 global $loader, $twig;
146 $authenticated = ControllerFactory::getController('auth', $loader, $twig)->call('restoreSession');
147 } else {
148 $authenticated = true;
149 }
150
151 if (isset($this->routes[$method])) {
152 if (!$authenticated) {
153 if ($this->checkRouteAndCall('guest', $method, $url)) return;
154 if ($this->checkRouteAndCall('*', $method, $url)) return;
155
156 // Redirection vers la page de connexion si l'utilisateur n'est pas connecté
157 header('Location: /login?redirect=' . urlencode($url));
158 return;
159 } else {
160 $role = $_SESSION['role'];
161 if ($this->checkRouteAndCall($role, $method, $url)) return;
162 if ($this->checkRouteAndCall('auth', $method, $url)) return;
163 if ($this->checkRouteAndCall('*', $method, $url)) return;
164 }
165
166 foreach ($this->routes[$method] as $target) {
167 foreach (array_keys($target) as $routeUrl) {
168 $pattern = preg_replace('/\/:([^\/]+)/', '/(?P<$1>[^/]+)', $routeUrl);
169 if (preg_match('#^' . $pattern . '(\?[^/]*=[^/]+)?$#', $url)) {
170 throw new UnauthorizedAccessException('Unauthorized access to route ' . $url . ' (' . $method . ')');
171 }
172 }
173 }
174 }
175
176 throw new RouteNotFoundException('Route ' . $url . ' (' . $method . ') not found');
177 }
178
186 private function checkRouteAndCall(string $middleware, string $method, string $url): bool
187 {
188 if (isset($this->routes[$method][$middleware])) {
189 foreach ($this->routes[$method][$middleware] as $routeUrl => $target) {
190 if ($this->callFunctionFromRoute($routeUrl, $target, $url)) return true;
191 }
192 }
193 return false;
194 }
195
203 private function callFunctionFromRoute(string $routeUrl, callable $target, string $url): bool
204 {
205 $pattern = preg_replace('/\/:([^\/]+)/', '/(?P<$1>[^/]+)', $routeUrl);
206 if (preg_match('#^' . $pattern . '(\?[^/]*=[^/]+)?$#', $url, $matches)) {
207 $params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
208 call_user_func_array($target, $params);
209 return true;
210 }
211 return false;
212 }
213
219 public function __wakeup(): void
220 {
221 throw new Exception("Cannot unserialize a singleton.");
222 }
223
228 private function __clone(): void
229 {
230 }
231}
Classe Router permettant de gérer les routes.
Definition Router.php:23
__construct()
Constructeur de la classe Router.
Definition Router.php:39
__wakeup()
Empêche la désérialisation de l'instance.
Definition Router.php:219
addRoute(string $method, string $url, callable $target, ?string $middleware=null)
Permet d'ajouter une route au tableau de routes du Router.
Definition Router.php:75
callFunctionFromRoute(string $routeUrl, callable $target, string $url)
Permet d'appeler la fonction associée à la route.
Definition Router.php:203
post(string $url, callable $target, ?string $middleware=null)
Ajout d'une route POST.
Definition Router.php:91
matchRoute()
Permet d'accéder à la route demandée.
Definition Router.php:139
put(string $url, callable $target, ?string $middleware=null)
Ajout d'une route PUT.
Definition Router.php:103
static Router $instance
Definition Router.php:28
checkRouteAndCall(string $middleware, string $method, string $url)
Permet de vérifier si une route existe.
Definition Router.php:186
static getInstance()
Permet de récupérer l'instance du Router.
Definition Router.php:47
__clone()
Empêche le clonage de l'instance.
Definition Router.php:228
static getController(string $controller, FilesystemLoader $loader, Environment $twig)
La méthode getController permet de récupérer un contrôleur.
$twig
Instance de Twig.
Definition twig.php:28
const BASE_URI
URI de base de l'application.
Definition const.php:26
$loader
Instance de FilesystemLoader.
Definition twig.php:23