phpstan / phpstan-doctrine

Doctrine extensions for PHPStan
MIT License
600 stars 98 forks source link

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

Open arderyp opened 2 years ago

arderyp commented 2 years ago

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 commented 2 years ago

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;
}
ondrejmirtes commented 2 years ago

Have you configured objectManagerLoader from the README?

arderyp commented 2 years ago

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();
ondrejmirtes commented 2 years ago

FYI @arnaud-lb might be fixable :)

arderyp commented 2 years ago

fixed typo in original post

arnaud-lb commented 2 years ago

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.

arderyp commented 2 years ago

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

arderyp commented 2 years ago

any luck here?