Skip to content

Commit

Permalink
Added new named constructor to create enum from mixed
Browse files Browse the repository at this point in the history
The current implementation of Enum requires to pass a valid enum value to class constructor. With this new named constructor we can just pass any value to enum and get an instance or unexpected value exception.
  • Loading branch information
michaelpetri committed Feb 10, 2021
1 parent 616601d commit 5cdc5da
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
30 changes: 27 additions & 3 deletions src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,24 @@ public function __construct($value)
$value = $value->getValue();
}

if (!$this->isValid($value)) {
throw new \UnexpectedValueException("Value '$value' is not part of the enum " . static::class);
}
static::assertValidValue($value);

/** @psalm-var T */
$this->value = $value;
}

/**
* @param mixed $value
* @return static
* @psalm-return static<T>
*/
public static function fromMixed($value): self
{
static::assertValidValue($value);

return new static($value);
}

/**
* @psalm-pure
* @return mixed
Expand Down Expand Up @@ -175,13 +185,27 @@ public static function toArray()
* @param $value
* @psalm-param mixed $value
* @psalm-pure
* @psalm-assert-if-true T $value
* @return bool
*/
public static function isValid($value)
{
return \in_array($value, static::toArray(), true);
}

/**
* Asserts valid enum value
*
* @psalm-pure
* @psalm-assert T $value
*/
public static function assertValidValue($value): void
{
if (!static::isValid($value)) {
throw new \UnexpectedValueException("Value '$value' is not part of the enum " . static::class);
}
}

/**
* Check if is valid enum key
*
Expand Down
15 changes: 15 additions & 0 deletions tests/EnumTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -332,4 +332,19 @@ public function testEnumValuesInheritance()
$inheritedEnumFixture = InheritedEnumFixture::VALUE();
new EnumFixture($inheritedEnumFixture);
}

/**
* @dataProvider isValidProvider
*/
public function testAssertValidValue($value, $isValid): void
{
if (!$isValid) {
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessage("Value '$value' is not part of the enum " . EnumFixture::class);
}

EnumFixture::assertValidValue($value);

self::assertTrue(EnumFixture::isValid($value));
}
}

0 comments on commit 5cdc5da

Please sign in to comment.