Completed
Pull Request — master (#719)
by
unknown
02:11
created

ContainerRepositoryFactory::getRepository()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.9197
c 0
b 0
f 0
cc 4
eloc 12
nc 4
nop 2
1
<?php
2
3
/*
4
 * This file is part of the Doctrine Bundle
5
 *
6
 * The code was originally distributed inside the Symfony framework.
7
 *
8
 * (c) Fabien Potencier <[email protected]>
9
 * (c) Doctrine Project, Benjamin Eberlei <[email protected]>
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace Doctrine\Bundle\DoctrineBundle\Repository;
16
17
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\ServiceRepositoryCompilerPass;
18
use Doctrine\ORM\EntityManagerInterface;
19
use Doctrine\ORM\Repository\RepositoryFactory;
20
use Psr\Container\ContainerInterface;
21
use Symfony\Bridge\Doctrine\RegistryInterface;
22
23
/**
24
 * Returns repositories that are registered in the container, or a default implementation.
25
 *
26
 * @author Ryan Weaver <[email protected]>
27
 */
28
final class ContainerRepositoryFactory implements RepositoryFactory
29
{
30
    public $container;
31
32
    private $genericRepositories = array();
33
34
    public function __construct(ContainerInterface $container)
35
    {
36
        $this->container = $container;
37
    }
38
39
    public function getRepository(EntityManagerInterface $entityManager, $entityName)
40
    {
41
        /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */
42
        $metadata = $entityManager->getClassMetadata($entityName);
43
        $entityClass = $metadata->name;
44
        $repositoryServiceId = $metadata->customRepositoryClassName;
45
46
        if (null !== $repositoryServiceId) {
47
            if (!$this->container->has($repositoryServiceId)) {
48
                throw new \RuntimeException(sprintf('Could not find the repository service for the "%s" entity. Make sure the "%s" service exists and is tagged with "%s"', $entityName, $repositoryServiceId, ServiceRepositoryCompilerPass::REPOSITORY_SERVICE_TAG));
49
            }
50
51
            return $this->container->get($repositoryServiceId);
52
        }
53
54
        $repositoryHash = $entityClass . spl_object_hash($entityManager);
55
        if (!isset($this->genericRepositories[$repositoryHash])) {
56
            $this->genericRepositories[$repositoryHash] = new DefaultServiceRepository($entityManager, $entityName);
57
        }
58
59
        return $this->genericRepositories[$repositoryHash];
60
    }
61
}
62