diff --git a/app/Server/Router/Router.php b/app/Server/Router/Router.php new file mode 100644 index 0000000000000000000000000000000000000000..c6d4249373602c3d6de945a5a89ea4071d82de03 --- /dev/null +++ b/app/Server/Router/Router.php @@ -0,0 +1,62 @@ +<?php + +namespace Server\Router; + +class Router { + private array $handlers; + private const METHOD_GET = 'GET'; + private const METHOD_POST = 'POST'; + + public function get(string $path, $handler): void + { + $this->addHandler(self::METHOD_GET, $path, $handler); + } + + public function post(string $path, $handler): void + { + $this->addHandler(self::METHOD_POST, $path, $handler); + } + + private function addHandler(string $method, string $path, $handler): void + { + $this->handlers[$method.$path] = [ + 'path' => $path, + 'method' => $method, + 'handler' => $handler, + ]; + } + + public function run() + { + $requstUri = parse_url($_SERVER['REQUEST_URI']); + $requestPath = $requstUri['path']; + $method = $_SERVER['REQUEST_METHOD']; + + $callback = null; + foreach ($this->handlers as $handler) { + if($handler['path'] === $requestPath && $method === $handler['method']) { + $callback = $handler['handler']; + } + } + + if(is_string($callback)) { + $parts = explode('@', $callback); + if(is_array($parts)) { + $className = array_shift($parts); + $handler = new $className; + + $method = array_shift($parts); + $callback = [$handler, $method]; + } + } + + if(!$callback) { + include 'Client/pages/Errors/NotFound.php'; + return; + } + + call_user_func_array($callback, [ + array_merge($_GET, $_POST) + ]); + } +} \ No newline at end of file diff --git a/app/router.php b/app/router.php deleted file mode 100644 index 7156e5c4dea8e7de894027f76c3b7fb0b37c0ccd..0000000000000000000000000000000000000000 --- a/app/router.php +++ /dev/null @@ -1,33 +0,0 @@ -<?php - -require_once './Controllers/PembelianController.php'; -require_once './Controllers/TicketController.php'; -require_once './Controllers/UserController.php'; -require_once './Controllers/EventController.php'; - -$eventController = new EventController(); -$pembelianController = new PembelianController(); -$ticketController = new TicketController(); -$userController = new UserController(); - -if ($_SERVER["REQUEST_METHOD"] == "POST") { - if (isset($_POST["eventAction"])) { - $eventController->handleRequest(); - } elseif (isset($_POST["ticketAction"])) { - $ticketController->handleRequest(); - } elseif (isset($_POST["userAction"])) { - $userController->handleRequest(); - } elseif (isset($_POST["purchaseAction"])) { - $pembelianController->handleRequest(); - } - -} elseif ($_SERVER["REQUEST_METHOD"] == "GET") { - if (isset($_GET["eventAction"]) && isset($_GET["eventId"])) { - $eventController->handleRequest(); - } elseif (isset($_GET["ticketAction"])) { - $ticketController->handleRequest(); - } elseif (isset($_GET["userAction"])) { - $userController->handleRequest(); - } -} -?> \ No newline at end of file