spatie / laravel-enum

Laravel support for spatie/enum
https://spatie.be/open-source
MIT License
341 stars 37 forks source link

mark enum values as obsolete/disabled? #83

Closed wivaku closed 3 years ago

wivaku commented 3 years ago

Is it possible to mark certain enum values as obsolete / disabled?

Use case example:

As a conceptual example:

/**
 * @method static self companyA()
 * @method static self companyB()
 * @method static self companyC()
 * @method static self companyAandC()
 */
class CompanyEnum extends Enum
{
    protected static function obsolete(): array
    {
        return [
          'companyA' => 'merged with company C',
          'companyC' => 'merged with company A',
        ];
    }
}

CompanyEnum::toValues(); // ['companyA', 'companyB', 'companyC', 'companyAandC']

CompanyEnum::toValidValues(); // ['companyB', 'companyAandC']
CompanyEnum::toObsolete(); // ['companyA' => 'merged with company C, 'companyC' => 'merged with company A']
Gummibeer commented 3 years ago

Hey,

the only way would be the @deprecated doc-tag - but this doesn't accept arguments and as we use magic methods you can't attach it to a real method. https://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_tags.deprecated.pkg.html

With PHP8.1 this will be possible as you have a real case COMPANY_A you can add a doc-tag to. But you can add these two static methods you named your own to the enum in question and do some array_filter, array_diff or whatever logic to reduce it to the ones you want there.

wivaku commented 3 years ago

Thanks Tom! Your PHP knowledge is impressive (and you fast responses are appreciated).

Here's my attempt at creating those two (example) methods:

/**
 * @method static self companyA()
 * @method static self companyB()
 * @method static self companyC()
 * @method static self companyAandC()
 */
final class CompanyEnum extends Enum
{
    protected static function obsolete(): array
    {
        return [
          'companyA' => 'merged with company C',
          'companyC' => 'merged with company A',
        ];
    }

    public static function toObsolete() {
        return method_exists(__CLASS__,'obsolete') ? self::obsolete() : [];
    }

    public static function toValidValues() {
        return array_values( array_diff(
            self::toValues(),
            array_keys(self::toObsolete())
        ) );
    }
}