philippurbschat.de/home/core/Router.php

47 lines
No EOL
1.9 KiB
PHP

<?php
class Router {
protected $controller = 'HomeController';
protected $method = 'index';
protected $params = [];
// Main Routing Logic
public function route() {
$url = $this->parseUrl();
$controllerPath = __DIR__ . '/../app/controllers/';
// Controller Check (Case-insensitive & kebab-case support)
if (isset($url[0])) {
$normalizedName = str_replace('-', '', ucwords(strtolower($url[0]), '-'));
$candidate = $normalizedName . 'Controller';
if (file_exists($controllerPath . $candidate . '.php')) {
$this->controller = $candidate;
unset($url[0]);
}
}
require_once $controllerPath . $this->controller . '.php';
$this->controller = new $this->controller;
// Method Check (Case-insensitive & kebab-case/snake_case support)
if (isset($url[1])) {
$rawMethod = strtolower($url[1]);
$normalizedMethod = str_replace(['-', '_'], '', $rawMethod);
foreach (get_class_methods($this->controller) as $methodName) {
if (strpos($methodName, '_') === 0) {
continue; // Skip magic/internal methods
}
if (strcasecmp($methodName, $rawMethod) === 0 || strcasecmp(str_replace(['-', '_'], '', $methodName), $normalizedMethod) === 0) {
$this->method = $methodName;
unset($url[1]);
break;
}
}
}
// Params & Execution
$this->params = $url ? array_values($url) : [];
call_user_func_array([$this->controller, $this->method], $this->params);
}
// URL Parser
private function parseUrl() {
if (isset($_GET['url'])) {
return explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
}
return [];
}
}