phpstan-doctrine icon indicating copy to clipboard operation
phpstan-doctrine copied to clipboard

QueryBuilder->getQuery->getResult() does not work properly when $indexBy is provided to ->from()

Open arderyp opened this issue 2 years ago • 8 comments

I am not sure if this is a problem with phpstan itself, or this repo.

This throws no error:

/** @return Users[] **/
 public function findCustom(string $type, string): array
{
    return $this->getEntityManager()->createQueryBuilder()
        ->select("user")
        ->from(Users::class, "user")
        ->where("user.type = :type")
        ->setParameter("type", $type)
        ->getQuery()
        ->getResult();
}

This throws findCustom() should return array<App\Entity\Users> but returns mixed.

/** @return Users[] **/
 public function findCustom(string $type, string, $indexBy = "user.uid"): array
{
    return $this->getEntityManager()->createQueryBuilder()
        ->select("user")
        ->from(Users::class, "user", $indexBy)
        ->where("user.type = :type")
        ->setParameter("type", $type)
        ->getQuery()
        ->getResult();
}

arderyp avatar Mar 15 '22 20:03 arderyp

I've gotten around the error with the following stub, but not sure if its the correct approach:

<?php

declare(strict_types=1);

namespace Doctrine\ORM;

abstract class AbstractQuery
{
    public const HYDRATE_OBJECT = 1;

    /**
     * see: https://github.com/phpstan/phpstan-doctrine/issues/301
     * @param string|int $hydrationMode
     * @@phpstan-ignore-next-line we are overriding the return type
     */
    public function getResult($hydrationMode = self::HYDRATE_OBJECT): array;
}

arderyp avatar Mar 15 '22 20:03 arderyp

Have you configured objectManagerLoader from the README?

ondrejmirtes avatar Mar 15 '22 21:03 ondrejmirtes

Yeah, I'm using the following:

#phpstan.neon
doctrine:
    objectManagerLoader: tests/object-manager.php
#tests/object-manager.php
<?php

declare(strict_types=1);

// @todo Symfony 5.4 update this file, see https://github.com/phpstan/phpstan-symfony

use App\Kernel;

require __DIR__ . '/../config/bootstrap.php';
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$kernel->boot();
return $kernel->getContainer()->get('doctrine')->getManager();

arderyp avatar Mar 15 '22 23:03 arderyp

FYI @arnaud-lb might be fixable :)

ondrejmirtes avatar Mar 17 '22 13:03 ondrejmirtes

fixed typo in original post

arderyp avatar Apr 13 '22 23:04 arderyp

INDEX BY and sub queries are currently not supported. When the extension can not determine the result type, mixed is returned (for the whole result or a part of the result).

I confirm that support for INDEX BY can probably be added.

arnaud-lb avatar May 27 '22 15:05 arnaud-lb

Sounds about right @arnaud-lb. If this should be an enhancement request, it would be really cool to have this support added.

arderyp avatar May 27 '22 15:05 arderyp

any luck here?

arderyp avatar Jul 16 '22 04:07 arderyp