Initial commit
This commit is contained in:
66
app/Core/Router.php
Normal file
66
app/Core/Router.php
Normal file
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
namespace App\Core;
|
||||
|
||||
class Router {
|
||||
protected $routes = [];
|
||||
|
||||
public function get($path, $callback) {
|
||||
$this->routes['GET'][$path] = $callback;
|
||||
}
|
||||
// Registers POST routes
|
||||
public function post($path, $callback) {
|
||||
$this->routes['POST'][$path] = $callback;
|
||||
}
|
||||
public function resolve($uri, $method) {
|
||||
// Strip query strings (e.g., /users?id=1 becomes /users)
|
||||
// In public/index.php
|
||||
|
||||
$path = parse_url($uri, PHP_URL_PATH);
|
||||
// var_dump($path);
|
||||
$callback = $this->routes[$method][$path] ?? null;
|
||||
|
||||
if (!$callback) {
|
||||
http_response_code(404);
|
||||
// echo "404 Not Found";
|
||||
$this->handleNotFound($path, $method);
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle 'Controller@method' strings
|
||||
if (is_string($callback)) {
|
||||
[$controllerName, $methodName] = explode('@', $callback);
|
||||
$controllerClass = "\\App\\Controllers\\" . $controllerName;
|
||||
$controller = new $controllerClass();
|
||||
$controller->$methodName();
|
||||
}
|
||||
}
|
||||
private function handleNotFound($path, $method) {
|
||||
$logger = new Logger();
|
||||
$isDebug = ($_ENV['APP_DEBUG'] ?? 'false') === 'true';
|
||||
|
||||
// 1. Log the failure for the developer
|
||||
$logMessage = "404 Not Found | Method: $method | URI: $path";
|
||||
$logger->error($logMessage);
|
||||
|
||||
http_response_code(404);
|
||||
|
||||
// 2. If Debug is ON, show detailed info in the browser
|
||||
if ($isDebug) {
|
||||
// echo "<h1>404 Not Found (Debug Mode)</h1>";
|
||||
// echo "<p><strong>Method:</strong> $method</p>";
|
||||
// echo "<p><strong>Attempted URI:</strong> $path</p>";
|
||||
// echo "<p><strong>Defined Routes:</strong></p><pre>";
|
||||
// print_r($this->routes[$method] ?? []);
|
||||
// echo "</pre>";
|
||||
|
||||
echo json_encode([ 'message' => 'Not Found', 'method' => $method, 'path' => $path]);
|
||||
} else {
|
||||
// Simple message for production
|
||||
echo "404 Not Found";
|
||||
}
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
?>
|
||||
Reference in New Issue
Block a user