122 lines
2.8 KiB
PHP
122 lines
2.8 KiB
PHP
<?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 {
|
|
public Neuron $get;
|
|
public Neuron $post;
|
|
public Neuron $json;
|
|
public Neuron $params;
|
|
public string $path;
|
|
public string $error;
|
|
public array $next;
|
|
|
|
/**
|
|
* __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);
|
|
|
|
$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();
|
|
}
|
|
|
|
/**
|
|
* Inicia la validación que se haya configurado.
|
|
*
|
|
* @return mixed
|
|
*/
|
|
public function validate(): mixed
|
|
{
|
|
if ($_SERVER['REQUEST_METHOD'] == 'GET')
|
|
$actual = $this->get;
|
|
else
|
|
$actual = $this->post;
|
|
|
|
if (Validator::validateList(static::paramRules(), $this->params) &&
|
|
Validator::validateList(static::getRules(), $this->get ) &&
|
|
Validator::validateList(static::rules(), $actual))
|
|
return Middleware::next($this);
|
|
|
|
if (isset(static::messages()[Validator::$lastFailed]))
|
|
$error = static::messages()[Validator::$lastFailed];
|
|
else {
|
|
|
|
$error = 'Error: validation failed of '.preg_replace('/\./', ' as ', Validator::$lastFailed, 1);
|
|
}
|
|
|
|
return static::onInvalid($error);
|
|
}
|
|
|
|
/**
|
|
* Reglas para el método actual.
|
|
*
|
|
* @return array
|
|
*/
|
|
public static function rules(): array {
|
|
return [];
|
|
}
|
|
|
|
/**
|
|
* Reglas para los parámetros por URL.
|
|
*
|
|
* @return array
|
|
*/
|
|
public static function paramRules(): array {
|
|
return [];
|
|
}
|
|
|
|
/**
|
|
* Reglas para los parámetros GET.
|
|
*
|
|
* @return array
|
|
*/
|
|
public static function getRules(): array {
|
|
return [];
|
|
}
|
|
|
|
/**
|
|
* Mensajes de error en caso de fallar una validación.
|
|
*
|
|
* @return array
|
|
*/
|
|
public static function messages(): array {
|
|
return [];
|
|
}
|
|
|
|
/**
|
|
* Función a ejecutar cuando se ha detectado un valor no válido.
|
|
*
|
|
* @param string $error
|
|
*
|
|
* @return mixed
|
|
*/
|
|
protected function onInvalid(string $error): mixed
|
|
{
|
|
print($error);
|
|
return null;
|
|
}
|
|
}
|