Flexible DTO Documentation

Allowed Properties

Sometimes you may want to define a list of properties that are allowed to be set on a DTO. This can be done by overriding the allowedProperties method in your DTO, returning an array of property names. This will prevent any properties not defined in the allowedProperties method from being set on the DTO.

class UserDTO extends DataTransferObject
{
    protected function allowedProperties(): array
    {
        return [
            'first_name',
            'last_name',
        ];
    }
}

$userDTO = new UserDTO([
    'first_name' => 'John',
    'last_name' => 'Doe',
    'company' => 'Acme Inc', // This value will be ignored
]);

$userDTO->getAll();
// ['first_name' => 'John', 'last_name' => 'Doe']

If you want to allow all properties to be set on the DTO, you can return ['*'] from the allowedProperties method. This is the default behavior if the allowedProperties method is not overridden.

class UserDTO extends DataTransferObject
{
    protected function allowedProperties(): array
    {
        return ['*'];
    }
}

If you want to enforce that only whitelisted properties can be passed into the DTO, you can set the $ignoreNonPermittedProperties to false; This will throw an InvalidArgumentException if a property is passed into the DTO that is not defined in the allowedProperties method.

class UserDTO extends DataTransferObject
{
    protected $ignoreNonPermittedProperties = false;

    protected function allowedProperties(): array
    {
        return [
            'first_name',
            'last_name',
        ];
    }
}

$userDTO = new UserDTO([
    'first_name' => 'John',
    'last_name' => 'Doe',
    'company' => 'Acme Inc', // Will throw an `InvalidArgumentException`
]);

// InvalidArgumentException: The property "company" is not an allowed property

By default, property names are case-sensitive. If you want to make them case-insensitive, you can set the $caseSensitive property to false.This will allow you to set properties with different casing than the defined properties, taking into account for hyphens, underscores, and camel case.

class UserDTO extends DataTransferObject
{
    protected $caseSensitive = false;

    protected function allowedProperties(): array
    {
        return [
            'first_name',
            'MIDDLENAME',
            'lastname',
            'company-name',
        ];
    }
}

$userDTO = new UserDTO([
    'firstName' => 'John',
    'Middle-Name' => 'William',
    'LastName' => 'Doe',
    'Company_Name' => 'Acme Inc',
]);

$userDTO->getAll();
// [
//    'first_name' => 'John',
//    'MIDDLENAME' => 'William',
//    'lastname' => 'Doe',
//    'company-name' => 'Acme Inc',
// ];