Completed
Pull Request — master (#658)
by Magnus
02:25
created

RepositoryAliasPass::process()   C

Complexity

Conditions 8
Paths 12

Size

Total Lines 47
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 47
rs 5.7377
cc 8
eloc 27
nc 12
nop 1
1
<?php
2
3
namespace Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler;
4
5
use Doctrine\Common\Persistence\Mapping\Driver\MappingDriver;
6
use Doctrine\ORM\Mapping\ClassMetadata;
7
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
8
use Symfony\Component\DependencyInjection\ContainerBuilder;
9
use Symfony\Component\DependencyInjection\Definition;
10
use Symfony\Component\DependencyInjection\Reference;
11
12
class RepositoryAliasPass implements CompilerPassInterface
13
{
14
    /**
15
     * {@inheritDoc}
16
     */
17
    public function process(ContainerBuilder $container)
18
    {
19
        if (!$container->hasParameter('doctrine.entity_managers')) {
20
            return;
21
        }
22
23
        $entityManagers = $container->getParameter('doctrine.entity_managers');
24
        $customRepositories = [];
25
26
        foreach ($entityManagers as $name => $serviceName) {
27
            $metadataDriverService = sprintf('doctrine.orm.%s_metadata_driver', $name);
28
29
            if (!$container->has($metadataDriverService)) {
30
                continue;
31
            }
32
33
            /** @var MappingDriver $metadataDriver */
34
            $metadataDriver = $container->get($metadataDriverService);
35
            $entityClassNames = $metadataDriver->getAllClassNames();
36
37
            foreach ($entityClassNames as $entityClassName) {
38
                $classMetadata = new ClassMetadata($entityClassName);
39
                $metadataDriver->loadMetadataForClass($entityClassName, $classMetadata);
40
41
                if ($classMetadata->customRepositoryClassName) {
42
                    $customRepositories[$classMetadata->customRepositoryClassName][] = [
43
                        0 => $entityClassName,
44
                        1 => $name,
45
                    ];
46
                }
47
            }
48
49
            foreach ($customRepositories as $repositoryClass => $entities) {
50
                if (count($entities) === 1) {
51
                    $definition = new Definition($repositoryClass);
52
                    $definition->setFactory(array(
53
                        new Reference('doctrine'),
54
                        'getRepository'
55
                    ));
56
                    $definition->setArguments($entities[0]);
57
                    $definition->setShared(false);
58
59
                    $container->setDefinition($repositoryClass, $definition);
60
                }
61
            }
62
        }
63
    }
64
}
65