You can install the package via composer:
composer require morningtrain/data-transfer-object-casters
To use the provided casters, add an attribute CastWith, to the property you want to cast.
class DTO extends DataTransferObject
{
#[CastWith(BoolCaster::class)]
public bool $bool;
}
The Boolean caster is used to cast the provided value to a boolean.
It uses FILTER_VALIDATE_BOOL, see the php docs for more information
The DateCaster will attempt to cast the provided value into a Carbon instance, using the provided format.
If no format is specified 'd.m.Y H:i:s' will be used.
use Morningtrain\DataTransferObjectCasters\Casters\DateCaster;
class DTO extends DataTransferObject
{
#[CastWith(DateCaster::class, format: 'Y-m-d')]
public Carbon $date;
}
The IntCaster casts the provided value to an integer using (int) cast.
The TrimCaster will trim the provided value, so no whitespace remains around the value.
The UppercaseFirstCaster will uppercase the first letter of the provided value, similar to php's ucfirst function.
Optionally, the caster can lowercase the rest of the string, like so.
use Morningtrain\DataTransferObjectCasters\Casters\UppercaseFirstCaster;
class DTO extends DataTransferObject
{
#[CastWith(UppercaseFirstCaster::class, lower: true)]
public string $ucFirstString;
}
If the provided value is not a string, it will return the provided value.
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.