Add Lib\Request.

This commit is contained in:
KJ 2024-02-17 21:16:06 -04:00
parent ee81246115
commit 49a16cc471
2 changed files with 59 additions and 32 deletions

57
src/Libs/Request.php Normal file
View File

@ -0,0 +1,57 @@
<?php
/**
* Request - DuckBrain
*
* Libería complementaria de la libería Router.
* Contiene el cuerpo básico de la petición http (POST, GET, JSON, etc).
*
* @author KJ
* @website https://kj2.me
* @licence MIT
*/
namespace Libs;
class Request extends Neuron {
/**
* @var Neuron $get Objeto con todos los valores de $_GET.
*/
public Neuron $get;
/**
* @var Neuron $post Objeto con todos los valores de $_POST.
*/
public Neuron $post;
/**
* @var Neuron $json Objeto con todos los valores json enviados.
*/
public Neuron $json;
/**
* @var mixed $params Objeto con todos los valores pseudovariables de la uri.
*/
public Neuron $params;
/**
* @var mixed $path Ruta actual tomando como raíz la instalación de DuckBrain.
*/
public string $path;
/**
* __construct
*
* @param string $path Ruta actual tomando como raíz la instalación de DuckBrain.
*/
public function __construct(string $path = '/') {
$this->path = $path;
$this->get = new Neuron($_GET);
$this->post = new Neuron($_POST);
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json")
$this->json = new Neuron(
(object) json_decode(trim(file_get_contents("php://input")), false)
);
else
$this->json = new Neuron();
$this->params = new Neuron();
}
}

View File

@ -133,36 +133,6 @@ class Router {
return new static();
}
/**
* @return Neuron
* Devuelve un objeto que contiene los atributos:
* post - Donde se encuentran los valores enviados por $_POST.
* get - Donde se encuentran los valores enviados por $_GET.
* json - Donde se encuentran los valores JSON enviados en el body.
*
*/
private static function getReq(): Neuron {
$req = new Neuron();
$req->get = new Neuron($_GET);
$req->post = new Neuron($_POST);
$req->json = new Neuron(static::get_json());
$req->params = new Neuron();
$req->path = static::currentPath();
return $req;
}
/**
* @return object
* Devuelve un objeto con los datos recibidos en JSON.
*/
private static function get_json(): object {
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json") {
return (object) json_decode(trim(file_get_contents("php://input")));
}
return (object) '';
}
/**
* Reconfigura el callback final de la última ruta.
*
@ -297,7 +267,7 @@ class Router {
}
/**
* Devuelve la ruta actual.
* Devuelve la ruta actual tomando como raíz la ruta de instalación de DuckBrain.
*
* @return string
*/
@ -336,7 +306,7 @@ class Router {
default => static::$get
};
$req = static::getReq();
$req = new Request(static::currentPath());
foreach ($routers as $router) { // revisa todos los routers para ver si coinciden con la ruta actual
if (preg_match_all('/^'.$router['path'].'\/?$/si',$path, $matches, PREG_PATTERN_ORDER)) {