Flexible DTO Documentation

Casting

Casting is performed on the input data after it has been validated. The $cast property is used to define the casting rules, where the key is the name of the property and the value is the casting rule.

use Mass6\FlexibleDTO\DTO;

class MyDTO extends DataTransferObject
{
    protected $casts = [
        'movie' => 'string',
        'releaseDate' => 'date',
        'rating' => 'float',
    ];

    protected function allowedProperties(): array
    {
        return [
            'movie',
            'releaseDate',
            'rating',
        ];
    }    
}

Casting Rules

The following casting rules are available.

array : Casts the value to an array.

bool, boolean : Casts the value to a boolean.

collection : Casts the value to an Illuminate\Support\Collection instance.

date : Casts the value to a Carbon\Carbon instance.

double : Casts the value to a double.

float : Casts the value to a float.

int, integer : Casts the value to an integer.

string : Casts the value to a string.

custom : Casts the value to a custom type. The custom type must implement the Mass6\FlexibleDTO\CastsProperties interface.

use Mass6\FlexibleDTO\DTO;

class MyDTO extends DataTransferObject
{
    protected function allowedProperties(): array
    {
        return [
            'movie',
            'releaseDate',
            'rating',
            'boxOffice',
        ];
    }

    protected function getRules(): array
    {
        return [
            'movie' => 'required|string',
            'releaseDate' => 'required|date',
            'rating' => 'required|integer',
            'boxOffice' => 'required|numeric',
        ];
    }

    protected function cast(): array
    {
        return [
            'movie' => 'string',
            'releaseDate' => 'date',
            'rating' => 'integer',
            'boxOffice' => MyCustomType::class,
        ];
    }
}

Custom Cast Types

Custom cast types can be defined by implementing the Mass6\FlexibleDTO\CastsProperties interface. The cast() method should return the value cast to the appropriate type/format.

use Mass6\FlexibleDTO\Castable;

class MyCustomType implements Castable
{
    public function cast($value)
    {
        return (float) $value;
    }
}