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

Static method return wrongly interpreted, causes return mismatch error #3400

Closed
kevinsmith opened this issue Jun 6, 2020 · 3 comments
Closed
Labels
Milestone

Comments

@kevinsmith
Copy link

Bug report

Using PHPStan v0.12.25. This may be related to #3273 but seemed different enough that it's worth reporting. If it is the same issue, I figure it might be helpful just to shed light on the bug from another angle.

I'm using a static factory method to create new instances of the generic Collection class. Since it's a static method (and therefore shouldn't be able to inherit the class type variable), I've declared a new method-level type variable and declared that the method returns a Collection of those method-level types. Unfortunately it causes this error:

Method Collection::ofType() should return Collection<U of Immutable> but returns Collection<Immutable>.

Code snippet that reproduces the problem

<?php

interface Immutable {}

/**
 * @template T of Immutable
 */
class Collection
{
    /** @var T[] */
    protected array $values = [];

    /**
     * @param T[] $values
     */
    protected function __construct(array $values = [])
    {
        $this->values = $values;
    }
    
    /**
     * @param class-string<U> $type
     *
     * @return Collection<U>
     *
     * @template U of Immutable
     */
    public static function ofType(string $type) : self
    {
        return new self();
    }
}

https://phpstan.org/r/d388d25d-7ccc-4f4f-89f2-7fafde83fa83

Expected output

I would expect there to be no errors. For reference, this works in Psalm: https://psalm.dev/r/6b3ad129ed

@ondrejmirtes ondrejmirtes added this to the Generics milestone Jun 6, 2020
@phpstan-bot
Copy link
Contributor

@kevinsmith After the latest commit in dev-master, PHPStan now reports different result with your code snippet:

@@ @@
-30: Method Collection::ofType() should return Collection<U of Immutable> but returns Collection<Immutable>.
+No errors

@ondrejmirtes
Copy link
Member

Fixed: phpstan/phpstan-src@c2b9e71

@github-actions
Copy link

github-actions bot commented Apr 5, 2022

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Apr 5, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

3 participants