Skip to content

Commit

Permalink
Merge pull request #135 from michaelpetri/feature/add-create-from-mixed
Browse files Browse the repository at this point in the history
Added new named constructor to create enum from mixed
  • Loading branch information
mnapoli committed Feb 12, 2021
2 parents 616601d + bd92d06 commit 9fcffe3
Show file tree
Hide file tree
Showing 2 changed files with 54 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 from($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
27 changes: 27 additions & 0 deletions tests/EnumTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,18 @@ public function testCreatingEnumWithInvalidValue($value)
new EnumFixture($value);
}

/**
* @dataProvider invalidValueProvider
* @param mixed $value
*/
public function testFailToCreateEnumWithInvalidValueThroughNamedConstructor($value): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessage('is not part of the enum MyCLabs\Tests\Enum\EnumFixture');

EnumFixture::from($value);
}

/**
* Contains values not existing in EnumFixture
* @return array
Expand Down Expand Up @@ -332,4 +344,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 9fcffe3

Please sign in to comment.