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

Query result type is not recognized if create the query builder on a trait

Open IndraGunawan opened this issue 1 year ago • 3 comments

this commit https://github.com/phpstan/phpstan-doctrine/commit/149cf71c3b470f815ad8ad658606e9217db22d9f makes the correct getResult return type if the method within the class, but it does not work if the query builder comes from a trait

trait MyTrait
{
	protected function getCustomQueryBuilder() {
		return $this->createQueryBuilder('t')
			->andWhere('t.enabled = true');
	}
}

class MyRepository
{
	use MyTrait;

	public function findBySomething(): array
	{
		$qb = $this->getCustomQueryBuilder()
			->andWhere('t.someInt = 1');
		return $qb->getQuery()->getResult();
	}

getting this error

 Method App\Repository\MyRepository::findBySomething() should return
         array<App\Entity\MyEntity> but returns mixed.

IndraGunawan avatar Nov 11 '24 09:11 IndraGunawan

@ondrejmirtes The problem is that OtherMethodQueryBuilderParser do not find the method in the file. Any idea how to address that?

janedbal avatar Nov 11 '24 09:11 janedbal

I don't know why it doesn't find that. Probably something related to traits :)

ondrejmirtes avatar Nov 11 '24 09:11 ondrejmirtes

Here is why:

  • Declaring class is the trait user (class), not the trait
    • Thus, it parses the file where the method is not present
    • But we cannot parse trait file as those make sense only when analysed within a class.

Failing test: https://github.com/phpstan/phpstan-doctrine/pull/627

janedbal avatar Nov 11 '24 10:11 janedbal