RelationalRepositoryFactory   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
c 1
b 0
f 0
lcom 1
cbo 0
dl 0
loc 57
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getRepository() 0 13 2
A createRepository() 0 7 2
1
<?php
2
3
/*
4
 * doctrine-orm-repositories (https://github.com/juliangut/doctrine-orm-repositories).
5
 * Doctrine2 ORM utility entity repositories.
6
 *
7
 * @license MIT
8
 * @link https://github.com/juliangut/doctrine-orm-repositories
9
 * @author Julián Gutiérrez <[email protected]>
10
 */
11
12
declare(strict_types=1);
13
14
namespace Jgut\Doctrine\Repository\ORM;
15
16
use Doctrine\Common\Persistence\ObjectRepository;
17
use Doctrine\ORM\EntityManager;
18
use Doctrine\ORM\EntityManagerInterface;
19
use Doctrine\ORM\Repository\RepositoryFactory;
20
21
/**
22
 * Relational entity repository factory.
23
 */
24
class RelationalRepositoryFactory implements RepositoryFactory
25
{
26
    /**
27
     * Default repository class.
28
     *
29
     * @var string
30
     */
31
    protected $repositoryClassName;
32
33
    /**
34
     * The list of EntityRepository instances.
35
     *
36
     * @var \Doctrine\Common\Persistence\ObjectRepository[]
37
     */
38
    private $repositoryList = [];
39
40
    /**
41
     * RelationalRepositoryFactory constructor.
42
     */
43
    public function __construct()
44
    {
45
        $this->repositoryClassName = RelationalRepository::class;
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function getRepository(EntityManagerInterface $entityManager, $entityName): ObjectRepository
52
    {
53
        /* @var \Doctrine\ORM\EntityManager $entityManager */
54
        $repositoryHash = $entityManager->getClassMetadata($entityName)->getName() . spl_object_hash($entityManager);
55
56
        if (array_key_exists($repositoryHash, $this->repositoryList)) {
57
            return $this->repositoryList[$repositoryHash];
58
        }
59
60
        $this->repositoryList[$repositoryHash] = $this->createRepository($entityManager, $entityName);
61
62
        return $this->repositoryList[$repositoryHash];
63
    }
64
65
    /**
66
     * Create a new repository instance for an entity class.
67
     *
68
     * @param EntityManager $entityManager
69
     * @param string        $entityName
70
     *
71
     * @return \Doctrine\Common\Persistence\ObjectRepository
72
     */
73
    private function createRepository(EntityManager $entityManager, $entityName): ObjectRepository
74
    {
75
        $metadata = $entityManager->getClassMetadata($entityName);
76
        $repositoryClassName = $metadata->customRepositoryClassName ?: $this->repositoryClassName;
77
78
        return new $repositoryClassName($entityManager, $metadata);
79
    }
80
}
81