phpstan-webmozart-assert icon indicating copy to clipboard operation
phpstan-webmozart-assert copied to clipboard

`allIsInstanceOf` does not work with generics

Open ruudk opened this issue 10 months ago • 1 comments

I noticed an interesting behavior in this extension.

With the following code:

class AssertReturn {
  /**
     * @template TClass of object
     * @param class-string<TClass> $class
     *
     * @throws InvalidArgumentException
     * @return list<TClass>
     */
    public static function allInstancesOf(mixed $list, string $class) : array
    {
        Assert::isList($list);
        dumpType($list); // Dumped type: list<mixed>
        Assert::allIsInstanceOf($list, $class);
        dumpType($list); // Dumped type: list<object>

        return $list;
    }
}

This is not what I was expecting or hoping for.

When using the Debugger I notice this:

Image

So it's related to the fact that I use generics to pass the TClass.

What's the best way to deal to mitigate this problem, if it's possible.

ruudk avatar Mar 03 '25 08:03 ruudk

I might be a good idea to investigate if phpdoc on webmozarts/assert is already enough to deal with everything. you can try maybe adding a test case and removing the implementation of it here and see what happens.

herndlm avatar Mar 03 '25 09:03 herndlm