WizdomWeb/app/Core/Router.php

82 lines
2.7 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* ============================================
* File: Router.php
* Path: /app/Core/
* Purpose: Core router handling HTTP methodspecific route dispatching.
* Version: 1.1
* Author: Wizdom Networks
* Usage: Handles all GET/POST routing to controllers.
* ============================================
*/
namespace WizdomNetworks\WizeWeb\Core;
use WizdomNetworks\WizeWeb\Utilities\Logger;
use WizdomNetworks\WizeWeb\Utilities\ErrorHandler;
class Router
{
private array $routes = [];
/**
* Registers a new route.
*
* @param string $path The URL path (e.g. /contact).
* @param string $controller The fully qualified controller class.
* @param string $method The method name in the controller.
* @param string $httpMethod HTTP method (GET, POST, etc.), defaults to GET.
*/
public function add(string $path, string $controller, string $method, string $httpMethod = 'GET'): void
{
$routeKey = strtoupper($httpMethod) . ':' . trim($path, '/');
Logger::debug("Registering route: [$httpMethod] $path -> $controller::$method");
$this->routes[$routeKey] = [$controller, $method];
}
/**
* Dispatch the request based on the path and HTTP method.
*
* @param string $path The requested path (from index.php).
*/
public function dispatch($path)
{
$httpMethod = $_SERVER['REQUEST_METHOD'];
$routeKey = $httpMethod . ':' . trim($path, '/');
Logger::debug("Dispatching [$httpMethod] $path");
if (isset($this->routes[$routeKey])) {
[$controllerName, $method] = $this->routes[$routeKey];
Logger::debug("Matched route -> $controllerName::$method");
try {
if (!class_exists($controllerName)) {
throw new \Exception("Controller not found: $controllerName");
}
$controller = new $controllerName();
if (!method_exists($controller, $method)) {
throw new \Exception("Method $method not found in $controllerName");
}
Logger::info("Executing controller: $controllerName::$method");
$controller->$method();
} catch (\Throwable $e) {
echo "<pre>";
echo "Exception: " . $e->getMessage() . "\n";
echo "File: " . $e->getFile() . "\n";
echo "Line: " . $e->getLine() . "\n";
echo "Trace:\n" . $e->getTraceAsString();
echo "</pre>";
exit;
}
} else {
Logger::error("Route not found: [$httpMethod] $path");
http_response_code(404);
echo "404 Not Found";
}
}
}