Files
duckbrain/src/Libs/Request.php
kj a1a15f492c refactor!: add Synapsis for dependency resolution and injection
- Remove Middleware class and custom callback handling logic.
- Implement Synapsis as a dependency injection container for automatic
resolution.
- Refactor Router to use Synapsis for process route callbacks and not found
handler.
- Update Request to remove middleware-specific properties and use
Router::$currentParams for path parameters.
2025-10-10 17:44:49 -03:00

152 lines
3.8 KiB
PHP

<?php
namespace Libs;
/**
* 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
*/
class Request extends Neuron
{
public Neuron $get;
public Neuron $post;
public Neuron $put;
public Neuron $patch;
public Neuron $delete;
public Neuron $json;
public Neuron $params;
public string $path;
public string $error;
public string $body;
/**
* __construct
*
* @param string $path Ruta actual tomando como raíz la instalación de DuckBrain.
*/
public function __construct()
{
$this->path = Router::currentPath();
$this->get = new Neuron($_GET);
$this->post = new Neuron($_POST);
$this->put = new Neuron();
$this->patch = new Neuron();
$this->delete = new Neuron();
$this->params = new Neuron(Router::$currentParams);
$this->body = file_get_contents("php://input");
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json") {
$this->json = new Neuron(
(object) json_decode(trim($this->body), false)
);
} else {
$this->json = new Neuron();
if (
in_array($_SERVER['REQUEST_METHOD'], ['PUT', 'PATCH', 'DELETE']) &&
preg_match('/^[^;?\/:@&=+$,]{1,255}[=]/', $this->body, $matches)
) {
// Con la expresión regular verificamos que sea un http
// query string válido y evitamos errores de memoria en caso
// de que el body tenga algo más grande que eso.
parse_str($this->body, $input_vars);
$this->{strtolower($_SERVER['REQUEST_METHOD'])} = new Neuron($input_vars);
}
}
// Corremos las validaciones configuradas
if (!$this->validate()) {
exit();
}
}
/**
* Inicia la validación que se haya configurado.
*
* @return bool
*/
public function validate(): bool
{
$actual = match ($_SERVER['REQUEST_METHOD']) {
'POST', 'PUT', 'PATCH', 'DELETE' => $this->{strtolower($_SERVER['REQUEST_METHOD'])},
default => $this->get
};
if (
Validator::validateList(static::paramRules(), $this->params) &&
Validator::validateList(static::getRules(), $this->get) &&
Validator::validateList(static::rules(), $actual)
) {
return true;
}
if (isset(static::messages()[Validator::$lastFailed])) {
$error = static::messages()[Validator::$lastFailed];
} else {
$error = 'Error: validation failed of ' . preg_replace('/\./', ' as ', Validator::$lastFailed, 1);
}
static::onInvalid($error);
return false;
}
/**
* Reglas para el método actual.
*
* @return array
*/
public function rules(): array
{
return [];
}
/**
* Reglas para los parámetros por URL.
*
* @return array
*/
public function paramRules(): array
{
return [];
}
/**
* Reglas para los parámetros GET.
*
* @return array
*/
public function getRules(): array
{
return [];
}
/**
* Mensajes de error en caso de fallar una validación.
*
* @return array
*/
public function messages(): array
{
return [];
}
/**
* Función a ejecutar cuando se ha detectado un valor no válido.
*
* @param string $error
*
* @return void
*/
public function onInvalid(string $error): void
{
http_response_code(422);
print($error);
}
}