Skip to content

Conditional return via static lookup array #9704

@ruudk

Description

@ruudk

Bug report

I'm trying to let PHPStan understand the following code using a static TYPES array to lookup a given type.

class HelloWorld
{
    private const TYPES = [
        'foo' => DateTime::class,
        'bar' => DateTimeImmutable::class,
    ];

    /**
     * @template T of key-of<self::TYPES>
     * @param T $type
     * @return self::TYPES[T]
     */
    public static function get(string $type) : ?object
    {
        $class = self::TYPES[$type] ?? null;
        if ($class === null) {
            return null;
        }

        return new $class('now');
    }
}

But whatever I try, it seems I cannot tell PHPStan that the return type will be an instance of the value from the self::TYPES constant array.

I also tried:

@return (self::TYPES[T] is defined ? self::TYPES[T] : null)

Code snippet that reproduces the problem

https://phpstan.org/r/e086655c-9d6d-4ed8-9f80-c3e3f33bdc9b

Expected output

I expect it to correctly understand the type.

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

It does, ❤️ PHPStan

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions