Skip to content

Commit a9ca8c4

Browse files
laylatichybrendt
andauthored
feat(validation): support nullable enums (#1739)
Co-authored-by: Brent Roose <[email protected]>
1 parent 5769ec2 commit a9ca8c4

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

packages/validation/src/Rules/IsEnum.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ public function __construct(
2626
private string $enum,
2727
private array $only = [],
2828
private array $except = [],
29+
private bool $orNull = false,
2930
) {
3031
if (! enum_exists($this->enum)) {
3132
throw new UnexpectedValueException(sprintf(
@@ -37,6 +38,10 @@ public function __construct(
3738

3839
public function isValid(mixed $value): bool
3940
{
41+
if ($this->orNull && $value === null) {
42+
return true;
43+
}
44+
4045
if ($value instanceof $this->enum) {
4146
return $this->isDesirable($value);
4247
}

packages/validation/src/Validator.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ public function validateValueForProperty(PropertyReflector $property, mixed $val
139139
}
140140

141141
if ($property->getType()->isEnum()) {
142-
$rules[] = new IsEnum($property->getType()->getName());
142+
$rules[] = new IsEnum(enum: $property->getType()->getName(), orNull: $property->isNullable());
143143
}
144144

145145
return $this->validateValue($value, $rules);

packages/validation/tests/Rules/IsEnumTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,4 +70,22 @@ public function test_validating_except_backed_enums(): void
7070
$this->assertTrue($rule->except(SomeBackedEnum::Test2)->isValid('one'));
7171
$this->assertFalse($rule->except(SomeBackedEnum::Test)->isValid('one'));
7272
}
73+
74+
public function test_validating_with_or_null(): void
75+
{
76+
$rule = new IsEnum(enum: SomeEnum::class, orNull: true);
77+
78+
$this->assertTrue(condition: $rule->isValid(value: null));
79+
$this->assertFalse(condition: $rule->isValid(value: 'NOPE_NOT_HERE'));
80+
$this->assertTrue(condition: $rule->isValid(value: 'VALUE_1'));
81+
}
82+
83+
public function test_failing_to_validate_with_or_null(): void
84+
{
85+
$rule = new IsEnum(enum: SomeEnum::class, orNull: false);
86+
87+
$this->assertFalse(condition: $rule->isValid(value: null));
88+
$this->assertFalse(condition: $rule->isValid(value: 'NOPE_NOT_HERE'));
89+
$this->assertTrue(condition: $rule->isValid(value: 'VALUE_1'));
90+
}
7391
}

0 commit comments

Comments
 (0)