Skip to content

Commit a33ddeb

Browse files
Add support for only and except in enum rules
1 parent 8d5b770 commit a33ddeb

File tree

3 files changed

+33
-4
lines changed

3 files changed

+33
-4
lines changed

docs/advanced-usage/validation-attributes.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,12 @@ public string $closure;
361361
```php
362362
#[Enum(ChannelType::class)]
363363
public string $closure;
364+
365+
#[Enum(ChannelType::class, only: [ChannelType::Email])]
366+
public string $closure;
367+
368+
#[Enum(ChannelType::class, except: [ChannelType::Email])]
369+
public string $closure;
364370
```
365371

366372
## ExcludeIf

src/Attributes/Validation/Enum.php

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ class Enum extends ObjectValidationAttribute
1313
public function __construct(
1414
protected string|EnumRule|RouteParameterReference $enum,
1515
protected ?EnumRule $rule = null,
16+
protected ?array $only = null,
17+
protected ?array $except = null,
1618
) {
1719
}
1820

@@ -27,9 +29,19 @@ public function getRule(ValidationPath $path): object|string
2729
return $this->rule;
2830
}
2931

30-
return $this->enum instanceof EnumRule
32+
$rule = $this->enum instanceof EnumRule
3133
? $this->enum
3234
: new EnumRule((string) $this->enum);
35+
36+
if ($this->only !== null) {
37+
$rule->only($this->only);
38+
}
39+
40+
if ($this->except !== null) {
41+
$rule->except($this->except);
42+
}
43+
44+
return $rule;
3345
}
3446

3547
public static function create(string ...$parameters): static

tests/Datasets/RulesDataset.php

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -219,11 +219,22 @@ function fixature(
219219
);
220220

221221
yield fixature(
222-
attribute: new Enum('enum_class'),
223-
expected: new EnumRule('enum_class'),
224-
expectCreatedAttribute: new Enum(new EnumRule('enum_class'))
222+
attribute: new Enum(DummyBackedEnum::class),
223+
expected: new EnumRule(DummyBackedEnum::class),
224+
expectCreatedAttribute: new Enum(new EnumRule(DummyBackedEnum::class))
225225
);
226226

227+
yield fixature(
228+
attribute: new Enum(DummyBackedEnum::class, only: [DummyBackedEnum::FOO]),
229+
expected: (new EnumRule(DummyBackedEnum::class))->only([DummyBackedEnum::FOO]),
230+
expectCreatedAttribute: new Enum((new EnumRule(DummyBackedEnum::class))->only(DummyBackedEnum::FOO))
231+
);
232+
233+
yield fixature(
234+
attribute: new Enum(DummyBackedEnum::class, except: [DummyBackedEnum::FOO]),
235+
expected: (new EnumRule(DummyBackedEnum::class))->except([DummyBackedEnum::FOO]),
236+
expectCreatedAttribute: new Enum((new EnumRule(DummyBackedEnum::class))->except(DummyBackedEnum::FOO))
237+
);
227238

228239
yield fixature(
229240
attribute: new ExcludeIf('field', true),

0 commit comments

Comments
 (0)