Skip to content

Return enums as collection requires all individual cases #6695

@phh

Description

@phh

Bug report

Originally created here: larastan/larastan#1129

When adding enums to my project, I'd like to return all the cases as a collection.

I kinda would expect this return type would work:

/** @return Collection<int, Role> */

Since the returned value of Role::cases()[0] is Role.

However, it requires all possible cases set:

/** @return Collection<int, Role::Admin|Role::Supporter|Role::User> */

So I'm getting this error:

Method App\Enums\Role::toCollection() should return Illuminate\Support\Collection<int, App\Enums\Role>
    but returns Illuminate\Support\Collection<int, App\Enums\Role::Admin|App\Enums\Role::Supporter|App\Enums\Role::User>

Is this the intended behavior?

Laravel code where the issue was found

enum Role: int
{
    case Admin = 1;
    case Supporter = 2;
    case User = 3;

    /** @return Collection<int, Role:> */
    public static function toCollection(): Collection
    {
        return collect(self::cases());
    }
}

Code snippet that reproduces the problem

https://phpstan.org/r/e7c7fd51-04fc-4f4f-a63e-3794812f3065

Expected output

I was expecting that return type Enum would be enough, not the individual Enum case.

Did PHPStan help you today? Did it make you happy in any way?

Happy to use PHPStan as a part of our CI. Thank you so much for making code cleaner and my IDE happier :>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions