soyhuce/data-transfer-object-casts

Common casts for spatie/data-transfer-object

0.1.1 2022-08-29 06:51 UTC

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status GitHub PHPStan Action Status Total Downloads

Common casts for spatie/data-transfer-object

Installation

You can install the package via composer:

composer require soyhuce/data-transfer-object-casts

Usage

BooleanCaster

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

CarbonImmutableCaster

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

StringEnumCaster

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

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.