duckbrain/src/Libs/Router.php

146 lines
4.0 KiB
PHP

<?php
namespace Libs;
use Libs\Request;
class Router{
private static $get = [];
private static $post = [];
private static $put = [];
private static $delete = [];
private static $last;
private function __construct(){}
private static function parse($path, $callback){
$path = preg_quote($path, '/');
$path = preg_replace(
['/\\\{[\w-]+\\\}/s'],
['([^\/]+)'],
$path);
if (!is_callable($callback)) {
$callback = 'Controllers\\'.$callback;
}
return [
'path'=> $path,
'callback' => $callback
];
}
public static function baseURI(){
return str_replace($_SERVER['DOCUMENT_ROOT'],'/', ROOT_DIR);
}
public static function redirect($uri){
header('Location: '.self::baseURI().substr($uri,1));
}
public static function middleware($middleware){ // Solo soporta un middleware a la vez
if (!isset(self::$last)) return;
$method = self::$last[0];
$index = self::$last[1];
self::$$method[$index]['middleware'] = 'Middlewares\\'.$middleware;
}
public static function get($path, $callback){
self::$get[] = self::parse($path, $callback);
self::$last = ['get', count(self::$get)-1];
return new static();
}
private static function params(){
$args = (object) '';
$args->get = new Params($_GET);
$args->post = new Params($_POST);
$args->json = new Params(self::get_json());
return $args;
}
private static function get_json(){
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json"){
return json_decode(trim(file_get_contents("php://input")));
}
return (object) '';
}
public static function post($path, $callback){
self::$post[] = self::parse($path, $callback);
self::$last = ['post', count(self::$post)-1];
return new static();
}
public static function put($path, $callback){
self::$put[] = self::parse($path, $callback);
self::$last = ['put', count(self::$put)-1];
return new static();
}
public static function delete($path, $callback){
self::$delete[] = self::parse($path, $callback);
self::$last = ['delete', count(self::$put)-1];
return new static();
}
public static function apply(){
$uri = preg_replace('/'.preg_quote(self::baseURI(), '/').'/',
'/', strtok($_SERVER['REQUEST_URI'], '?'), 1);
$routers = [];
switch ($_SERVER['REQUEST_METHOD']){
case 'POST':
$routers = self::$post;
break;
case 'PUT':
$routers = self::$put;
break;
case 'DELETE':
$routers = self::$delete;
break;
default:
$routers = self::$get;
break;
}
foreach ($routers as $router){
if (preg_match_all('/^'.$router['path'].'\/?$/si',$uri, $matches)){
unset($matches[0]);
$args = self::params();
if (isset($matches[1])){
$params = [];
foreach ($matches as $match){
if (!empty($match))
$params[] = "$match[0]";
}
if (isset($router['middleware'])){
$middleware = explode('::',$router['middleware']);
$data = call_user_func_array($middleware, [$router['callback'], $args, $params]);
}else
$params[] = $args;
$data = call_user_func_array($router['callback'], $params);
}else{
if (isset($router['middleware'])){
$middleware = explode('::',$router['middleware']);
$data = call_user_func_array($middleware, [$router['callback'], $args]);
}else
$data = call_user_func_array($router['callback'], [$args]);
}
if (isset($data)){
header('Content-Type: application/json');
print(json_encode($data));
}
return;
}
}
header("HTTP/1.0 404 Not Found");
echo '<h2 style="text-align: center;margin: 25px 0px;">Error 404 - Página no encontrada</h2>';
}
}