Type Cast
Input from a form, a query string, or a JSON body arrives as strings or mixed types, and PHP's own casts accept almost anything. (int) 'abc' quietly returns 0, and (bool) 'false' returns true. TypeCast provides conversions with three levels of strictness, so the code can decide whether a bad value is a default, a missing value, or an error. It also converts collections between arrays, objects, and iterables.
Minimal Setup
TypeCast is a static class. Choose a conversion by its name:
use Windwalker\Utilities\TypeCast;
TypeCast::toArray(new ArrayObject(['a' => 1])); // ['a' => 1]
TypeCast::toString(['a' => 1]); // 'Array()'Showcase: Reading Request Parameters
The following example reads a list query. Each parameter is converted strictly, and falls back to a default when the value is not valid:
use Windwalker\Utilities\TypeCast;
function listOptions(array $query): array
{
return [
'limit' => TypeCast::safeInteger($query['limit'] ?? null)
?? 20,
'active' => TypeCast::safeBoolean($query['active'] ?? null)
?? false,
'tags' => TypeCast::mapAs(
explode(',', $query['tags'] ?? ''),
'string',
),
];
}
listOptions(['limit' => '50', 'active' => true, 'tags' => 'php,go']);
// ['limit' => 50, 'active' => true, 'tags' => ['php', 'go']]
listOptions(['limit' => 'many']);
// ['limit' => 20, 'active' => false, 'tags' => ['']]Two results come from the strict conversions: 'many' is not an integer, so the default applies, and an absent active becomes null, so the default false applies.
Three Levels of Conversion
Each conversion comes in three forms. They differ in what they do when a value does not fit:
tryand thetry*()methods convert as PHP would, so most scalar values produce a result. A value that cannot be converted givesnull.safeand thesafe*()methods convert only when the conversion is lossless. Otherwise they returnnull.mustand themust*()methods do the same assafe, but throw aCastingExceptioninstead of returningnull.
TypeCast::tryInteger('12abc'); // 12
TypeCast::safeInteger('12abc'); // null
TypeCast::mustInteger('12abc'); // throws CastingExceptionPass true as the last argument of a try*() method to make it strict. In strict mode, TypeCast::tryInteger(12.5, true) returns null.
INFO
The safe methods accept only real booleans for safeBoolean(). The string '1' and the integer 1 give null, while tryBoolean() converts them.
Conversion Methods
These methods convert the whole value, with no fallback:
toArray()converts an object or aTraversableto an array. Pass$recursiveto convert nested objects too, and$filterto apply the visibility rules of Attributes.toObject()converts an array to an object, and returns an object unchanged. Pass$classto create another class.toIterable()returns an iterable as it is, an object's public properties as an array, and any other value cast to an array.toString()converts a value to a string. An array becomesArray(), and an object becomes[Object ClassName]. Passtrueas the second argument to dump arrays and objects, or useforceString().extractEnum()returns the value of a backed enum, or the name of a unit enum.mapAs()converts every item of an array to a type, or to a class.
TypeCast::mapAs(['1', '2'], 'int'); // [1, 2]
TypeCast::mapAs([['id' => 1]], Item::class);
// Creates an Item from each element.mapAs() accepts array, string, int, float, and bool, as well as a class name. Any other name throws an InvalidArgumentException.
Type Checks Before Conversion
canSafeConvert() tells you whether a value can be converted to a type without losing information. Use it when the conversion logic depends on the answer:
TypeCast::canSafeConvert('1', 'int'); // true
TypeCast::canSafeConvert(1.5, 'int'); // falseDumping Every Property
dumpAll() returns the values of all properties of an object, including private and protected ones. It is meant for debugging and tests. The result is keyed by property name.
Magic Methods
Each conversion has a short name generated by __callStatic():
tryInteger(),tryFloat(),tryNumeric(),tryString(),tryBoolean(),tryArray(),tryObject().safeInteger(),safeFloat(),safeNumeric(),safeString(),safeBoolean(),safeArray(),safeObject().mustInteger(),mustFloat(),mustNumeric(),mustString(),mustBoolean(),mustArray(),mustObject().
Any other method name throws a BadMethodCallException.
Method Summary
| Method | Parameters | Description |
|---|---|---|
try() | mixed $value, string $type, bool $strict = false | Converts to a type, or returns null. |
safe() | mixed $value, string $type | Strict conversion, or null. |
must() | mixed $value, string $type | Strict conversion, or throws CastingException. |
canSafeConvert() | mixed $value, string $type | Whether a lossless conversion exists. |
toArray() | mixed $data, bool $recursive = false, bool $onlyDumpable = false, ?int $filter = null | Converts to an array. |
toIterable() | mixed $iterable | Returns an iterable. |
toObject() | array|object $array, bool $recursive = false, string $class = stdClass::class | Converts to an object. |
toString() | mixed $data, bool $dump = false | Converts to a string. |
forceString() | mixed $data | Same as toString() with dumping on. |
mapAs() | array $src, string $typeOrClass | Converts each item to a type or class. |
extractEnum() | \UnitEnum $data | Returns the backed value, or the name. |
dumpAll() | object $object | All property values, including private ones. |
try*(), safe*(), must*() | mixed $value, bool $strict = false | Typed shortcuts, through __callStatic(). |
Related
- Helpers:
Env::get()returns string values that often need converting. - Exceptions: the
CastingExceptionthrown bymust().