|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace GemaDigital\Rules; |
| 4 | + |
| 5 | +use Closure; |
| 6 | +use Illuminate\Contracts\Validation\ValidationRule; |
| 7 | +use Illuminate\Database\Query\Builder; |
| 8 | + |
| 9 | +final class ScopedUniqueRule implements ValidationRule |
| 10 | +{ |
| 11 | + public function __construct( |
| 12 | + protected string $model, |
| 13 | + protected ?string $field = null, |
| 14 | + protected ?int $ignoreId = null, |
| 15 | + ) {} |
| 16 | + |
| 17 | + /** |
| 18 | + * Create a new instance from a var_export export. |
| 19 | + * |
| 20 | + * @param array<string, mixed> $state |
| 21 | + */ |
| 22 | + public static function __set_state(array $state): static |
| 23 | + { |
| 24 | + return new self( |
| 25 | + model: $state['model'], |
| 26 | + field: $state['field'] ?? null, |
| 27 | + ignoreId: $state['ignoreId'] ?? null, |
| 28 | + ); |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Run the validation rule. |
| 33 | + * |
| 34 | + * @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail |
| 35 | + */ |
| 36 | + public function validate(string $attribute, mixed $value, Closure $fail): void |
| 37 | + { |
| 38 | + if ($value === null) { |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + $model = app($this->model); |
| 43 | + $field = $this->field ?? $model->getKeyName(); |
| 44 | + |
| 45 | + /** @var Builder */ |
| 46 | + $query = is_array($value) |
| 47 | + ? $model->whereIn($field, $value) |
| 48 | + : $model->where($field, $value); |
| 49 | + |
| 50 | + if ($this->ignoreId) { |
| 51 | + is_array($value) |
| 52 | + ? $model->whereNotIn($model->getKeyName(), $this->ignoreId) |
| 53 | + : $query->whereNot($model->getKeyName(), $this->ignoreId); |
| 54 | + |
| 55 | + } |
| 56 | + |
| 57 | + if ($query->count() > 0) { |
| 58 | + $fail(__('validation.unique')); |
| 59 | + |
| 60 | + return; |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments