Search code examples
phpdoctrinephpstan

PHPStan with Doctrine and find() - Unable to resolve the template type T


I have this particular code:

<?php declare(strict_types = 1);

interface ObjectManager
{
    /**
     * @param string $className The class name of the object to find.
     * @param mixed  $id        The identity of the object to find.
     * @psalm-param class-string<T> $className
     *
     * @return object|null The found object.
     * @psalm-return T|null
     *
     * @template T of object
     */
    public function find($className, $id);
}

abstract class AbstractAppEntityRepository
{
    protected ObjectManager $manager;

    public function __construct(ObjectManager $manager)
    {
        $this->manager = $manager;
    }

    /**
     * @template T
     * @param class-string<T> $className
     * @param int|string|array<string, string|int> $id
     * @return T|null
     */
    protected function findEntity(string $className, array | int | string $id)
    {
        /**
         * @var T|null $entity
         * @phpstan-var T|null $entity
         */
        $entity = $this->manager->find($className, $id);

        return $entity;
    }
}

The PHPStan playground is giving me an error when after analyzing it:

Line 39 - Unable to resolve the template type T in call to method ObjectManager::find()

Link to the playground: LINK

Would use some help, as I do not know how to manage with this. Thank you in advance for any help!


Solution

  • It would help to declare your type variable as @template T of object: https://phpstan.org/r/587e228b-0c21-4def-bfed-4cd53b955a4b

    The inline @phpstan-var isn’t neccesary either.