BenSampo / laravel-enum

Simple, extensible and powerful enumeration implementation for Laravel.
https://sampo.co.uk/blog/using-enums-in-laravel
MIT License
2k stars 164 forks source link

Spatie Laravel-data cast #289

Closed nikrovir closed 1 year ago

nikrovir commented 1 year ago

Hello! Anyone have idea how to cast string into enum using Spatie Laravel-data package?

spawnia commented 1 year ago

If you solved this, please share.

nikrovir commented 1 year ago

I solve my problem in this way:

use BenSampo\Enum\Enum;
use BenSampo\Enum\Exceptions\InvalidEnumMemberException;
use Spatie\LaravelData\Casts\Cast;
use Spatie\LaravelData\Support\DataProperty;

class EnumCaster implements Cast
{
    /**
     * @throws InvalidEnumMemberException
     */
    public function cast(DataProperty $property, mixed $value, array $context): Enum
    {
        $type = $this->type ?? $property->type->findAcceptedTypeForBaseType(Enum::class);

        if ($value instanceof $type) {
            return $value;
        }

        return $type::fromValue($value);
    }
}