From 27bde2e165378c0c9367e4c9a78115d23111a78f Mon Sep 17 00:00:00 2001 From: Kenneth Trecy Tobias Date: Wed, 23 Aug 2023 23:20:33 +0800 Subject: [PATCH] internal(validation): add new rule to check if a record matches criteria --- app/Validation/DatabaseRules.php | 33 ++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/app/Validation/DatabaseRules.php b/app/Validation/DatabaseRules.php index 58e2dc3f..75894971 100644 --- a/app/Validation/DatabaseRules.php +++ b/app/Validation/DatabaseRules.php @@ -3,6 +3,7 @@ namespace App\Validation; use App\Contracts\OwnedResource; +use App\Models\BaseResourceModel; class DatabaseRules { public function ensure_ownership( @@ -39,4 +40,36 @@ public function ensure_ownership( return true; } + + public function has_column_value_in_list( + $value, + string $parameters, + array $data, + ?string &$error = null + ): bool { + $parameters = explode(",", $parameters); + + if ( + count($parameters) < 2 + || !(model($parameters[0]) instanceof BaseResourceModel) + || !in_array($parameters[1], model($parameters[0])->allowedFields) + ) { + $error = 'A resource model, column to check, and acceptable list of column values is required' + .' in "{0}" to check if the selected option in {field} is allowed.'; + return false; + } + + $model = model($parameters[0]); + $id = $value; + $column = $parameters[1]; + $allowed_values = array_slice($parameters, 2); + $entity = $model->find($id); + + if (!in_array($entity->$column, $allowed_values)) { + $error = "{field} does not match the acceptable values."; + return false; + } + + return true; + } }