Skip to content

Types

Type coercion

On denormalization a value written in another form is converted to the type, when it is the same value: '42' to int is 42, '4.2' is not. Normalization never converts.

$mapper->denormalize('42', 'int'); // 42
$mapper->denormalize('-0', 'int'); // 0
$mapper->denormalize('42.0', 'int'); // 42
$mapper->denormalize(42.0, 'int'); // 42
$mapper->denormalize(42, 'float'); // 42.0
$mapper->denormalize('4.2', 'float'); // 4.2
$mapper->denormalize('1e3', 'float'); // 1000.0
$mapper->denormalize('.5', 'float'); // 0.5
$mapper->denormalize(42, 'string'); // '42'
$mapper->denormalize(4.2, 'string'); // '4.2'
$mapper->denormalize(1, 'bool'); // true
$mapper->denormalize('0', 'bool'); // false
$mapper->denormalize('true', 'bool'); // true
$mapper->denormalize('yes', 'bool'); // true
$mapper->denormalize('off', 'bool'); // false

A stdClass (such as from json_decode()) is accepted as the data of a list, an array, a shape or a class, also with strict types. Other objects are not.

$mapper->denormalize((object) ['a' => '1'], 'array<string, int>'); // ['a' => 1]

Replace a coercer of the mapper by the name of its type: int, float, string, bool or array.

use TypeLang\Mapper\Coercer\CoercerInterface;
use TypeLang\Mapper\Coercer\FloatCoercer;
use TypeLang\Mapper\Mapper;
/**
* @template-implements CoercerInterface<float>
*/
final class DecimalCommaCoercer implements CoercerInterface
{
public function __construct(
private readonly FloatCoercer $float = new FloatCoercer(),
) {}
public function coerce(mixed $value): ?float
{
if (\is_string($value)) {
$value = \str_replace(',', '.', $value);
}
return $this->float->coerce($value);
}
}
$mapper = new Mapper(coercers: ['float' => new DecimalCommaCoercer()]);
$mapper->denormalize('4,2', 'float'); // 4.2

A coercer returns the converted value or null when the value cannot be converted.