Skip to content

Nullable value for enum #77

Closed
Closed
@KartaviK

Description

@KartaviK

To do this, I had to expand Enum to support null values.
It is also a good idea to support null as a separate enum value.

I recommend to use array_key_exist() instead of isset() for validate Enum value:

New:

public static function __callStatic($name, $arguments)
{
    $array = static::toArray();

    if (\array_key_exists($name, $array)) {
        return new static($array[$name]);
    }

    throw new \BadMethodCallException("No static method or enum constant '$name' in class " . \get_called_class());
}

Example:

<?php

final class MyEnum extends \MyCLabs\Enum\Enum
{
    public const UNDEFINED = null;
}

I can put null to __construct()

<?php

/** @var string|int|null $value */

$enum = new MyEnum($value); // It can take null

But i cant do it with static:

<?php

$enum = MyEnum::UNDEFINED(); // I'll catch an exception

And finally i can remove excess ? operator from methods and constructors:

This is look better

public function someMethod(MyEnum $enum)
{
    if (!$enum->equals(MyEnum::UNDEFINED()) {
        // ...
    }
}

then this

<?php

public function someMethod(?MyEnum $enum)
{
    if ($enum !== null) {
        // do ...
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions