Repository (Doctrine\ORM\EntityRepository) does not accept Doctrine\Persistence\ObjectRepository

Viewed 1375

When upgrading doctrine/persistence from 1.0 to 1.3 I encountered a problem with static code analysis.

Repository (Doctrine\ORM\EntityRepository) does not accept                    
         Doctrine\Persistence\ObjectRepository.     

The problem is with this

<?php
declare(strict_types=1);

namespace Appbundle\Repository\Company;

class CompanyRepository
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;

    /**
     * @var EntityRepository
     */
    private $entityRepository;

    /**
     * @var ProfileRepository
     */
    private $profileRepository;

    public function __construct(
        EntityManagerInterface $entityManager,
    ) {
        $this->entityManager = $entityManager;
        $this->entityRepository = $entityManager->getRepository(Company::class);
    }

The code works as getRepository reuturns EntityRepository but return type of getReposiry is ObjectRepository and is not compatible. Worked with version 1.0. Anyone got idea what it might be?

2 Answers

This error is correct. EntityManagerInterface inherits getRepository method from ObjectManager interface, where ObjectRepository is typehinted.

So you can't rely on EntityRepository to be returned from the method as the implementation can choose to return just ObjectRepository.

You should probably typehint for something else, like EntityManager instead.

Related