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 = Router::$params ?? 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) ) { // With the regular expression, we verify that it is a valid // http query string and avoid memory errors in case // the body contains something larger than that. parse_str($this->body, $input_vars); $this->{strtolower($_SERVER['REQUEST_METHOD'])} = new Neuron($input_vars); } } // Run configured validations if (!$this->validate()) { exit(); } } /** * Starts the configured validation. * * @return bool */ public function validate(): bool { $actual = match ($_SERVER['REQUEST_METHOD']) { 'POST', 'PUT', 'PATCH', 'DELETE' => $this->{strtolower($_SERVER['REQUEST_METHOD'])}, default => $this->get }; // Merge uploaded files ($_FILES) into the body data set so the file rules // (file/image/mimes and the routed min/max/required...) can validate // uploads through a Request. $this->post is left untouched. $body = empty($_FILES) ? $actual : new Neuron(array_merge(get_object_vars($actual), $_FILES)); if ( Validator::validateList(static::paramRules(), $this->params) && Validator::validateList(static::getRules(), $this->get) && Validator::validateList(static::rules(), $body) ) { return true; } $error = Validator::message( Validator::$lastFailed, static::messages(), static::attributes() ); static::onInvalid($error); return false; } /** * Rules for the current method. * * @return array */ public function rules(): array { return []; } /** * Rules for URL parameters. * * @return array */ public function paramRules(): array { return []; } /** * Rules for GET parameters. * * @return array */ public function getRules(): array { return []; } /** * Error messages in case a validation fails. * * @return array */ public function messages(): array { return []; } /** * Human-readable names for the fields. * * Forwarded to Validator::message() so the :attribute marker in the error * text can be replaced with a friendlier name (e.g. "edad" => "la edad"). * * @return array */ public function attributes(): array { return []; } /** * Function to execute when an invalid value has been detected. * * @param string $error * * @return void */ public function onInvalid(string $error): void { http_response_code(422); print($error); } }