Skip to content

Commit d33c58e

Browse files
author
Michael Petri
committed
Added new named constructor to create enum from mixed
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.
1 parent 616601d commit d33c58e

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

src/Enum.php

+23-3
Original file line numberDiff line numberDiff line change
@@ -61,14 +61,20 @@ public function __construct($value)
6161
$value = $value->getValue();
6262
}
6363

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

6866
/** @psalm-var T */
6967
$this->value = $value;
7068
}
7169

70+
/** @param mixed $value */
71+
public static function fromMixed($value): self
72+
{
73+
self::assertValidValue($value);
74+
75+
return new static($value);
76+
}
77+
7278
/**
7379
* @psalm-pure
7480
* @return mixed
@@ -175,13 +181,27 @@ public static function toArray()
175181
* @param $value
176182
* @psalm-param mixed $value
177183
* @psalm-pure
184+
* @psalm-assert-if-true T $value
178185
* @return bool
179186
*/
180187
public static function isValid($value)
181188
{
182189
return \in_array($value, static::toArray(), true);
183190
}
184191

192+
/**
193+
* Asserts valid enum value
194+
*
195+
* @psalm-pure
196+
* @psalm-assert T $value
197+
*/
198+
public static function assertValidValue($value): void
199+
{
200+
if (!self::isValid($value)) {
201+
throw new \UnexpectedValueException("Value '$value' is not part of the enum " . static::class);
202+
}
203+
}
204+
185205
/**
186206
* Check if is valid enum key
187207
*

tests/EnumTest.php

+15
Original file line numberDiff line numberDiff line change
@@ -332,4 +332,19 @@ public function testEnumValuesInheritance()
332332
$inheritedEnumFixture = InheritedEnumFixture::VALUE();
333333
new EnumFixture($inheritedEnumFixture);
334334
}
335+
336+
/**
337+
* @dataProvider isValidProvider
338+
*/
339+
public function testAssertValidValue($value, $isValid): void
340+
{
341+
if (!$isValid) {
342+
$this->expectException(\UnexpectedValueException::class);
343+
$this->expectExceptionMessage("Value '$value' is not part of the enum " . EnumFixture::class);
344+
}
345+
346+
EnumFixture::assertValidValue($value);
347+
348+
self::assertTrue(EnumFixture::isValid($value));
349+
}
335350
}

0 commit comments

Comments
 (0)