Skip to content

Metadata

Property types

The type of a property and its strictness.

Every option is shown in each metadata source: choose the tab of the source you use. When a source cannot express an option, its tab says what is used instead.

The type of the property: any supported type. When it is not specified, the native type of the property is used.

use TypeLang\Mapper\Mapping\MapType;
final class User
{
#[MapType('list<non-empty-string>')]
public array $tags = [];
}
$mapper->denormalize(['tags' => ['php', 'mapper']], User::class);
// User { tags: ['php', 'mapper'] }

Different types for normalization (read) and denormalization (write), given on the get and set hooks of a property (PHP 8.4):

  • attributes: a type on the property itself sets both types;
  • PHPDoc: the tags of the hooks, then @var, which sets only the read type when the set hook takes another type;
  • reflection: the read type is the declared type of the property, the write type is the parameter type of the set hook;
  • config: read_type or write_type of a direction the property does not take part in, such as write_type without a set hook, is an error.
use TypeLang\Mapper\Mapping\MapType;
final class User
{
private string $value = '';
public mixed $id {
#[MapType('int')]
get => (int) $this->value;
#[MapType('positive-int')]
set(mixed $id) {
$this->value = (string) $id;
}
}
}
$user = $mapper->denormalize(['id' => '42'], User::class);
$user->id; // 42
$mapper->normalize($user); // ['id' => 42]

Disables type coercion for the value of the property and its nested values, or enables it with false. Overrides the configuration option.

use TypeLang\Mapper\Mapping\MapType;
final class User
{
#[MapType('int', strict: true)]
public int $id;
}
$mapper->denormalize(['id' => 42], User::class); // User { id: 42 }