Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use DTO in a query builder #555

Open
asispts opened this issue Mar 22, 2024 · 7 comments
Open

Use DTO in a query builder #555

asispts opened this issue Mar 22, 2024 · 7 comments

Comments

@asispts
Copy link

asispts commented Mar 22, 2024

Can the following code work without manually defining the return type, i.e adding /** @var UserDto[] */?

final class Repository
{
    public function __construct(
        private EntityManagerInterface $em
    ) {
    }

    /**
     * @return UserDto[]
     */
    public function findAll(): array
    {
        $qb = $this->em->createQueryBuilder()
            ->select(\sprintf('NEW %s(u.id, u.email)', UserDto::class))
            ->from(User::class, 'u')
            ->getQuery();

        /** @var UserDto[] */
        return $qb->getResult();
    }

    public function findByEmail(string $email): ?UserDto
    {
        $qb = $this->em->createQueryBuilder()
            ->select(\sprintf('NEW %s(u.id, u.email)', UserDto::class))
            ->from(User::class, 'u')
            ->where('u.email = :email')
            ->setParameter('email', $email)
            ->getQuery();

        /** @var UserDto|null */
        return $qb->getOneOrNullResult();
    }
}
@ondrejmirtes
Copy link
Member

This should work fine. Have you configured objectManagerLoader (see README)?

@janedbal
Copy link
Contributor

Readme states that NEW should work. Are you suggesting it does not?

Most DQL features are supported, including GROUP BY, DISTINCT, all flavors of JOIN, arithmetic expressions, functions, aggregations, NEW, etc.

@asispts
Copy link
Author

asispts commented Mar 22, 2024

Yeah, I've added tests/object-manager.php. I still got an error

Method Repository::findByEmail() should return UserDto|null but returns mixed.

The first method should have no issue.

@ondrejmirtes
Copy link
Member

Are you on latest versions of PHPStan and phpstan-doctrine?

@asispts
Copy link
Author

asispts commented Mar 22, 2024

Yeah, tested on the latest version

phpstan: 1.10.64
phpstan-doctrine: 1.3.64

@ondrejmirtes
Copy link
Member

There are many test cases for this scenario starting on this line

I guess you might have to reproduce your issue either in tests here (probably in QueryBuilderGetQueryDynamicReturnTypeExtensionTest), or in a separate repository.

@asispts
Copy link
Author

asispts commented Mar 22, 2024

I'll try that

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants