Skip to content
Some core and sharing classes for Windwalker components.

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:

php
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:

php
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:

  • try and the try*() methods convert as PHP would, so most scalar values produce a result. A value that cannot be converted gives null.
  • safe and the safe*() methods convert only when the conversion is lossless. Otherwise they return null.
  • must and the must*() methods do the same as safe, but throw a CastingException instead of returning null.
php
TypeCast::tryInteger('12abc'); // 12
TypeCast::safeInteger('12abc'); // null
TypeCast::mustInteger('12abc'); // throws CastingException

Pass 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 a Traversable to an array. Pass $recursive to convert nested objects too, and $filter to apply the visibility rules of Attributes.
  • toObject() converts an array to an object, and returns an object unchanged. Pass $class to 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 becomes Array(), and an object becomes [Object ClassName]. Pass true as the second argument to dump arrays and objects, or use forceString().
  • 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.
php
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:

php
TypeCast::canSafeConvert('1', 'int');   // true
TypeCast::canSafeConvert(1.5, 'int');   // false

Dumping 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 ​

MethodParametersDescription
try()mixed $value, string $type, bool $strict = falseConverts to a type, or returns null.
safe()mixed $value, string $typeStrict conversion, or null.
must()mixed $value, string $typeStrict conversion, or throws CastingException.
canSafeConvert()mixed $value, string $typeWhether a lossless conversion exists.
toArray()mixed $data, bool $recursive = false, bool $onlyDumpable = false, ?int $filter = nullConverts to an array.
toIterable()mixed $iterableReturns an iterable.
toObject()array|object $array, bool $recursive = false, string $class = stdClass::classConverts to an object.
toString()mixed $data, bool $dump = falseConverts to a string.
forceString()mixed $dataSame as toString() with dumping on.
mapAs()array $src, string $typeOrClassConverts each item to a type or class.
extractEnum()\UnitEnum $dataReturns the backed value, or the name.
dumpAll()object $objectAll property values, including private ones.
try*(), safe*(), must*()mixed $value, bool $strict = falseTyped shortcuts, through __callStatic().
  • Helpers: Env::get() returns string values that often need converting.
  • Exceptions: the CastingException thrown by must().

Released under the MIT License.