Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nullable value for enum #77

Closed
KartaviK opened this issue Oct 25, 2018 · 4 comments
Closed

Nullable value for enum #77

KartaviK opened this issue Oct 25, 2018 · 4 comments
Labels

Comments

@KartaviK
Copy link
Contributor

KartaviK commented Oct 25, 2018

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 ...
    }
}
@KartaviK
Copy link
Contributor Author

Implementation:
#78

@willemstuursma
Copy link
Contributor

willemstuursma commented Oct 25, 2018

You can combine isset and array_key_exists to get best of both worlds.

if (isset($array[$name]) || \array_key_exists($name, $array)) {

isset is a language construct and a bit faster than array_key_exists.

@KartaviK
Copy link
Contributor Author

Yes, I agree. In this case, array_key_exists will be executed secondary if isset returns false

@mnapoli
Copy link
Member

mnapoli commented Oct 27, 2018

Really nice fix and thanks @willemstuursma too, merging!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants