Common casts for spatie/data-transfer-object
You can install the package via composer:
composer require soyhuce/data-transfer-object-casts
Casts the input into boolean, if applicable.
use Soyhuce\DataTransferObjectCasts\BooleanCaster;
use Spatie\DataTransferObject\Attributes\DefaultCast;
use Spatie\DataTransferObject\DataTransferObject;
#[DefaultCast('bool', BooleanCaster::class)]
class MyDTO extends DataTransferObject
{
public bool $bool;
}
$dto = new MyDTO(
bool: 'true',
);
$dto->bool; // true
Cast the input into a CarbonImmutable instance. If the input is not a string, it will be returned as is.
By default, the format is '!Y-m-d H:i:s'
.
use Carbon\CarbonImmutable;
use Soyhuce\DataTransferObjectCasts\CarbonImmutableCaster;
use Spatie\DataTransferObject\Attributes\CastWith;
use Spatie\DataTransferObject\Attributes\DefaultCast;
use Spatie\DataTransferObject\DataTransferObject;
#[DefaultCast(CarbonImmutable::class, CarbonImmutableCaster::class)]
class MyDTO extends DataTransferObject
{
public CarbonImmutable $dateTime;
#[CastWith(CarbonImmutableCaster::class, '!Y-m-d')]
public CarbonImmutable $date;
}
$dto = new MyDTO(
dateTime: '2022-08-11 14:44:45',
date: '2022-08-01',
);
$dto->dateTime; // CarbonImmutable instance
$dto->date; // CarbonImmutable instance
Cast the input into a backed string enum.
use Soyhuce\DataTransferObjectCasts\StringEnumCaster;
use Spatie\DataTransferObject\Attributes\CastWith;
use Spatie\DataTransferObject\DataTransferObject;
#[CastWith(StringEnumCaster::class)]
enum StringEnum: string
{
case ok = 'ok';
case nok = 'nok';
}
class MyDTO extends DataTransferObject
{
public StringEnum $stringEnum;
}
$dto = new MyDTO(
stringEnum: 'ok',
);
$dto->stringEnum; // StringEnum::ok
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.