From aed4f15e2209a95c7f95b2d8ae89c92c044830f6 Mon Sep 17 00:00:00 2001 From: Riyyi Date: Mon, 10 May 2021 18:06:20 +0200 Subject: [PATCH] Add CRUD create/update form validation --- app/controllers/CrudController.php | 4 ++-- app/model/Model.php | 24 ++++++++++++++++++++++-- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/app/controllers/CrudController.php b/app/controllers/CrudController.php index 1a55311..11b93c3 100644 --- a/app/controllers/CrudController.php +++ b/app/controllers/CrudController.php @@ -88,7 +88,7 @@ class CrudController extends PageController { $token = Session::validateToken($_POST); - $token && $model->fill($_POST) && $model->save() + $token && $model->fill($_POST) && $model->validate() && $model->save() ? $this->setAlertNext('success', "$modelName successfully created.") : $this->setAlertNext('danger', "$modelName could not be created!"); @@ -171,7 +171,7 @@ class CrudController extends PageController { $token = Session::validateToken($_PUT); - $token && $model->fill($_PUT) && $model->save() + $token && $model->fill($_PUT) && $model->validate() && $model->save() ? $this->setAlertNext('success', "$modelName successfully updated.") : $this->setAlertNext('danger', "$modelName could not be updated!"); } diff --git a/app/model/Model.php b/app/model/Model.php index 60b5902..c18c5c1 100644 --- a/app/model/Model.php +++ b/app/model/Model.php @@ -222,8 +222,7 @@ abstract class Model { // Set other attributes foreach ($this->getAttributes() as $attribute) { - if (_exists($fill, $attribute) || - (isset($fill[$attribute]) && $fill[$attribute] === '0')) { + if (isset($fill[$attribute])) { // Escape sequences are only interpreted with double quotes! $this->{$attribute} = preg_replace('/\r\n?/', "\n", $fill[$attribute]); } @@ -232,6 +231,27 @@ abstract class Model { return true; } + public function validate(): bool + { + foreach ($this->getAttributes() as $attribute) { + + $required = false; + foreach ($this->rules as $rule) { + if ($rule[0] == $attribute && $rule[2] == 1) { + $required = true; + break; + } + } + + // Exit if rule is marked 'required' but empty, "0" is not empty! + if ($required && empty($this->{$attribute}) && $this->{$attribute} !== "0") { + return false; + } + } + + return true; + } + public function getPrimaryKey(): string { return $this->primaryKey;