54 lines
1.4 KiB
PHP
54 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace Kavalanche\Router;
|
|
|
|
/**
|
|
* @author wojtek
|
|
*/
|
|
class Router {
|
|
|
|
private $allowedMethods = [
|
|
'get',
|
|
'post'
|
|
];
|
|
private $routes = [];
|
|
|
|
public function request($method, $path, $callback) {
|
|
$route = new Route();
|
|
$route->method = $method;
|
|
$route->path = $path;
|
|
$route->callback = $callback;
|
|
$this->routes[] = $route;
|
|
}
|
|
|
|
public function get($path, $callback) {
|
|
return $this->request('get', $path, $callback);
|
|
}
|
|
|
|
public function post($path, $callback) {
|
|
return $this->request('post', $path, $callback);
|
|
}
|
|
|
|
public function dispatch() {
|
|
$requestMethod = strtolower($_SERVER['REQUEST_METHOD']);
|
|
$requestUri = parse_url($_SERVER['REQUEST_URI']);
|
|
foreach ($this->routes as $route) {
|
|
$path = str_replace('/', '\/', $route->path);
|
|
$path = '/^' . $path . '\/?$/';
|
|
if (in_array($requestMethod, $this->allowedMethods, true)) {
|
|
if ($requestMethod === $route->method) {
|
|
if (preg_match($path, $requestUri['path'], $params) === 1) {
|
|
array_shift($params);
|
|
call_user_func_array($route->callback, $params);
|
|
exit;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
http_response_code(404);
|
|
throw new Exception('Route not found!');
|
|
exit;
|
|
}
|
|
|
|
}
|