Router.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace App\Core;
  3. use App\Core\Exceptions\NotFoundException;
  4. /*
  5. * Gestiona las rutas de la aplicación.
  6. */
  7. class Router
  8. {
  9. public Request $request;
  10. public Response $response;
  11. /*
  12. * Almacena todas las rutas de la aplicación.
  13. */
  14. protected array $routes = [];
  15. public function __construct(Request $request, Response $response)
  16. {
  17. $this->request = $request;
  18. $this->response = $response;
  19. }
  20. /*
  21. * Almacena rutas para el método GET.
  22. */
  23. public function get(string $path, $callback)
  24. {
  25. $this->routes['get'][$path] = $callback;
  26. }
  27. /*
  28. * Almacena rutas para el método POST.
  29. */
  30. public function post(string $path, $callback)
  31. {
  32. $this->routes['post'][$path] = $callback;
  33. }
  34. /*
  35. * Ejecuta la acción de la petición.
  36. */
  37. public function resolve()
  38. {
  39. $path = $this->request->getPath();
  40. $method = $this->request->getMethod();
  41. $callback = $this->routes[$method][$path] ?? false;
  42. if ($callback === false) {
  43. // $this->response->setStatusCode(404);
  44. // return Application::$app->view->renderView('404');
  45. throw new NotFoundException();
  46. }
  47. if (is_string($callback)) {
  48. return Application::$app->view->renderOnlyView($callback);
  49. }
  50. if (is_array($callback)) {
  51. // Crea la instancia del controlador.
  52. Application::$app->controller = new $callback[0]();
  53. Application::$app->controller->action = $callback[1];
  54. $callback[0] = Application::$app->controller;
  55. // Ejecuta los middlewares del controlador.
  56. foreach (Application::$app->controller->getMiddlewares() as $middleware) {
  57. $middleware->execute();
  58. }
  59. }
  60. return call_user_func($callback, $this->request, $this->response);
  61. }
  62. }