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->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); } } $this->params = new Neuron(); } /** * Corre las validaciones e intenta continuar con la pila de callbacks. * * @return mixed */ public function handle(): mixed { if ($this->validate()) return Middleware::next($this); return null; } /** * 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); } return static::onInvalid($error); } /** * 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 false */ public function onInvalid(string $error): false { http_response_code(422); print($error); return false; } }