The mapper will map values to the type provided to the map()
function, this can be any notation of native types, arrays or objects.
$mapper = new \Jerodev\DataMapper\Mapper();
// Native types
$mapper->map('int', '5'); // 5
$mapper->map('string', 5); // '5'
$mapper->map('bool', '5'); // true
// Arrays
$mapper->map('int[]', ['1', true, 3]); // [1, 1, 3]
$mapper->map('array<string, float>', [
1 => 3,
'foo' => '008',
]); // ['1' => 3.0, 'foo' => 8.0]
When passing a fully namespaced class name to the mapper, it will map data directly to public properties on objects. If these properties have types defined either using types introduced in PHP7.4 or through PHPDoc, the mapper will attempt to cast the data to these types.
For example: imagine having an User
class with the public properties $id
and $name
:
class User
{
public int $id;
public string $name;
}
To map data from an array we simply pass the class name and an array with data to the mapper.
$mapper = new \Jerodev\DataMapper\Mapper();
$user = $mapper->map(User::class, [
'id' => '5',
'name' => 'John Doe',
]);
// User {
// +id: 5,
// +name: "John Doe",
// }
More information about object mapping can be found here.