File tree 2 files changed +42
-3
lines changed
2 files changed +42
-3
lines changed Original file line number Diff line number Diff line change @@ -61,14 +61,24 @@ public function __construct($value)
61
61
$ value = $ value ->getValue ();
62
62
}
63
63
64
- if (!$ this ->isValid ($ value )) {
65
- throw new \UnexpectedValueException ("Value ' $ value' is not part of the enum " . static ::class);
66
- }
64
+ self ::assertValidValue ($ value );
67
65
68
66
/** @psalm-var T */
69
67
$ this ->value = $ value ;
70
68
}
71
69
70
+ /**
71
+ * @param mixed $value
72
+ * @return static
73
+ * @psalm-return static<T>
74
+ */
75
+ public static function fromMixed ($ value ): self
76
+ {
77
+ self ::assertValidValue ($ value );
78
+
79
+ return new static ($ value );
80
+ }
81
+
72
82
/**
73
83
* @psalm-pure
74
84
* @return mixed
@@ -175,13 +185,27 @@ public static function toArray()
175
185
* @param $value
176
186
* @psalm-param mixed $value
177
187
* @psalm-pure
188
+ * @psalm-assert-if-true T $value
178
189
* @return bool
179
190
*/
180
191
public static function isValid ($ value )
181
192
{
182
193
return \in_array ($ value , static ::toArray (), true );
183
194
}
184
195
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 (!self ::isValid ($ value )) {
205
+ throw new \UnexpectedValueException ("Value ' $ value' is not part of the enum " . static ::class);
206
+ }
207
+ }
208
+
185
209
/**
186
210
* Check if is valid enum key
187
211
*
Original file line number Diff line number Diff line change @@ -332,4 +332,19 @@ public function testEnumValuesInheritance()
332
332
$ inheritedEnumFixture = InheritedEnumFixture::VALUE ();
333
333
new EnumFixture ($ inheritedEnumFixture );
334
334
}
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
+ }
335
350
}
You can’t perform that action at this time.
0 commit comments