Completed
Pull Request — master (#719)
by
unknown
07:43
created

ContainerRepositoryFactory   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 4
dl 0
loc 37
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B getRepository() 0 22 4
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
class ContainerRepositoryFactory implements RepositoryFactory
29
{
30
    public $container;
31
32
    private $registry;
33
34
    private $genericRepositories = array();
35
36
    public function __construct(ContainerInterface $container, RegistryInterface $registry)
37
    {
38
        $this->container = $container;
39
        $this->registry = $registry;
40
    }
41
42
    public function getRepository(EntityManagerInterface $entityManager, $entityName)
43
    {
44
        /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */
45
        $metadata = $entityManager->getClassMetadata($entityName);
46
        $entityClass = $metadata->name;
47
        $repositoryServiceId = $metadata->customRepositoryClassName;
48
49
        if (null !== $repositoryServiceId) {
50
            if (!$this->container->has($repositoryServiceId)) {
51
                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));
52
            }
53
54
            return $this->container->get($repositoryServiceId);
55
        }
56
57
        $repositoryHash = $entityClass . spl_object_hash($entityManager);
58
        if (!isset($this->genericRepositories[$repositoryHash])) {
59
            $this->genericRepositories[$repositoryHash] = new DefaultServiceRepository($entityManager, $entityName);
60
        }
61
62
        return $this->genericRepositories[$repositoryHash];
63
    }
64
}
65