You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This method is a convenience helper to "wrap" a value (or an enum instance) into the corresponding enum instance. It is especially useful when you accept mixed input (an enum instance, a case name, a backing value, or null) and want to normalize it into the enum instance.
209
+
210
+
Signature:
211
+
```php
212
+
public static function wrap(self|string|int|null $value, bool $strict = false): ?self
213
+
```
214
+
215
+
Behavior notes:
216
+
- If an actual enum instance (same enum) is passed, it is returned unchanged.
217
+
- If null is passed, the method throws an error if `$strict = true`, otherwise it returns null.
218
+
- If a backing value is passed (int or string), the method attempts to resolve it using `tryFrom()` (for BackedEnum) or `tryFromName()` (for pure enums).
219
+
- For int-backed enums, numeric strings (e.g. `'1'`) are accepted: they are converted to integer and processed as numeric backing values.
220
+
- When a string is passed and no backing match is found, `wrap()` will try to resolve it as a case name via `tryFromName()`.
221
+
- By default (`$strict = false`) the method returns null if no enum case matches. When `$strict = true`, the method throws a `ValueError` if the value cannot be converted to a valid enum instance.
PureEnum::wrap('MISSING', true); // throws ValueError: '"MISSING" is not a valid backing value for enum "Namespace\PureEnum"'
249
+
```
250
+
251
+
Notes on error message:
252
+
- When `$strict` is true and no match is found, `wrap()` throws a `ValueError` with a message similar to:
253
+
'"<value>" is not a valid backing value for enum "<FullyQualifiedClassName>"'
254
+
255
+
This helper is useful in input normalization flows (e.g. DTOs, HTTP handlers, form processors) where you want to accept several forms of enum input and consistently obtain an enum instance or a null.
256
+
207
257
### Inspection
208
258
This helper permits check the type of enum (`isPure()`,`isBacked()`) and if enum contains a case name or value (`has()`, `doesntHave()`, `hasName()`, `doesntHaveName()`, `hasValue()`, `doesntHaveValue()`).
0 commit comments