Skip to content

Commit 478612e

Browse files
committed
Throw when when calling Enum::getDescription() with invalid values
1 parent fb04edc commit 478612e

File tree

3 files changed

+10
-11
lines changed

3 files changed

+10
-11
lines changed

src/Enum.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ abstract class Enum implements EnumContract, Castable, Arrayable, JsonSerializab
5656
public function __construct(mixed $enumValue)
5757
{
5858
if (! static::hasValue($enumValue)) {
59-
throw new InvalidEnumMemberException($enumValue, $this);
59+
throw new InvalidEnumMemberException($enumValue, static::class);
6060
}
6161

6262
$this->value = $enumValue;
@@ -302,7 +302,8 @@ public static function getValues(string|array|null $keys = null): array
302302
*/
303303
public static function getKey(mixed $value): string
304304
{
305-
return array_search($value, static::getConstants(), true);
305+
return array_search($value, static::getConstants(), true)
306+
?: throw new InvalidEnumMemberException($value, static::class);
306307
}
307308

308309
/**

src/Exceptions/InvalidEnumMemberException.php

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,13 @@
33
namespace BenSampo\Enum\Exceptions;
44

55
use Exception;
6-
use BenSampo\Enum\Enum;
76

87
class InvalidEnumMemberException extends Exception
98
{
109
/**
11-
* Create an InvalidEnumMemberException.
12-
*
13-
* @param mixed $invalidValue
14-
* @param \BenSampo\Enum\Enum $enum
15-
* @return void
10+
* @param class-string<\BenSampo\Enum\Enum> $enum
1611
*/
17-
public function __construct($invalidValue, Enum $enum)
12+
public function __construct(mixed $invalidValue, string $enum)
1813
{
1914
$invalidValueType = gettype($invalidValue);
2015
$enumValues = implode(', ', $enum::getValues());

tests/EnumAttributeDescriptionTest.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace BenSampo\Enum\Tests;
44

5+
use BenSampo\Enum\Exceptions\InvalidEnumMemberException;
56
use Exception;
67
use PHPUnit\Framework\TestCase;
78
use BenSampo\Enum\Tests\Enums\DescriptionFromAttribute;
@@ -26,8 +27,10 @@ public function test_an_exception_is_thrown_when_accessing_a_description_which_i
2627
DescriptionFromAttribute::InvalidCaseWithMultipleDescriptions()->description;
2728
}
2829

29-
public function test_an_exception_is_not_thrown_when_accessing_a_description_for_an_invalid_value()
30+
public function test_an_exception_is_thrown_when_accessing_a_description_for_an_invalid_value()
3031
{
31-
$this->assertSame('', DescriptionFromAttribute::getDescription('invalid'));
32+
$this->expectException(InvalidEnumMemberException::class);
33+
34+
DescriptionFromAttribute::getDescription('invalid');
3235
}
3336
}

0 commit comments

Comments
 (0)