Skip to content

Commit

Permalink
internal(validation): add new rule to check if a record matches criteria
Browse files Browse the repository at this point in the history
  • Loading branch information
KennethTrecy committed Aug 23, 2023
1 parent 1554f54 commit 27bde2e
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions app/Validation/DatabaseRules.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Validation;

use App\Contracts\OwnedResource;
use App\Models\BaseResourceModel;

class DatabaseRules {
public function ensure_ownership(
Expand Down Expand Up @@ -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;
}
}

0 comments on commit 27bde2e

Please sign in to comment.