File tree Expand file tree Collapse file tree 2 files changed +54
-3
lines changed Expand file tree Collapse file tree 2 files changed +54
-3
lines changed Original file line number Diff line number Diff line change @@ -61,14 +61,24 @@ 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+ static ::assertValidValue ($ value );
6765
6866 /** @psalm-var T */
6967 $ this ->value = $ value ;
7068 }
7169
70+ /**
71+ * @param mixed $value
72+ * @return static
73+ * @psalm-return static<T>
74+ */
75+ public static function from ($ value ): self
76+ {
77+ static ::assertValidValue ($ value );
78+
79+ return new static ($ value );
80+ }
81+
7282 /**
7383 * @psalm-pure
7484 * @return mixed
@@ -175,13 +185,27 @@ public static function toArray()
175185 * @param $value
176186 * @psalm-param mixed $value
177187 * @psalm-pure
188+ * @psalm-assert-if-true T $value
178189 * @return bool
179190 */
180191 public static function isValid ($ value )
181192 {
182193 return \in_array ($ value , static ::toArray (), true );
183194 }
184195
196+ /**
197+ * Asserts valid enum value
198+ *
199+ * @psalm-pure
200+ * @psalm-assert T $value
201+ */
202+ public static function assertValidValue ($ value ): void
203+ {
204+ if (!static ::isValid ($ value )) {
205+ throw new \UnexpectedValueException ("Value ' $ value' is not part of the enum " . static ::class);
206+ }
207+ }
208+
185209 /**
186210 * Check if is valid enum key
187211 *
Original file line number Diff line number Diff line change @@ -48,6 +48,18 @@ public function testCreatingEnumWithInvalidValue($value)
4848 new EnumFixture ($ value );
4949 }
5050
51+ /**
52+ * @dataProvider invalidValueProvider
53+ * @param mixed $value
54+ */
55+ public function testFailToCreateEnumWithInvalidValueThroughNamedConstructor ($ value ): void
56+ {
57+ $ this ->expectException (\UnexpectedValueException::class);
58+ $ this ->expectExceptionMessage ('is not part of the enum MyCLabs\Tests\Enum\EnumFixture ' );
59+
60+ EnumFixture::from ($ value );
61+ }
62+
5163 /**
5264 * Contains values not existing in EnumFixture
5365 * @return array
@@ -332,4 +344,19 @@ public function testEnumValuesInheritance()
332344 $ inheritedEnumFixture = InheritedEnumFixture::VALUE ();
333345 new EnumFixture ($ inheritedEnumFixture );
334346 }
347+
348+ /**
349+ * @dataProvider isValidProvider
350+ */
351+ public function testAssertValidValue ($ value , $ isValid ): void
352+ {
353+ if (!$ isValid ) {
354+ $ this ->expectException (\UnexpectedValueException::class);
355+ $ this ->expectExceptionMessage ("Value ' $ value' is not part of the enum " . EnumFixture::class);
356+ }
357+
358+ EnumFixture::assertValidValue ($ value );
359+
360+ self ::assertTrue (EnumFixture::isValid ($ value ));
361+ }
335362}
You can’t perform that action at this time.
0 commit comments