Passed
Pull Request — master (#151)
by
unknown
02:56
created

ChainManagerRegistry   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
eloc 17
c 1
b 0
f 0
dl 0
loc 46
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
A getManagerForClass() 0 9 3
A getRepository() 0 9 3
A getManagers() 0 8 1
1
<?php
2
3
namespace Zenstruck\Foundry;
4
5
use Doctrine\Persistence\ManagerRegistry;
6
use Doctrine\Persistence\ObjectManager;
7
use Doctrine\Persistence\ObjectRepository;
8
9
class ChainManagerRegistry
10
{
11
    /** @var array<ManagerRegistry> */
12
    private $managerRegistries;
13
14
    /** @param array<ManagerRegistry> $managerRegistries */
15
    public function __construct(array $managerRegistries)
16
    {
17
        if (count($managerRegistries) === 0) {
18
            throw new \InvalidArgumentException('no manager registry provided');
19
        }
20
21
        $this->managerRegistries = $managerRegistries;
22
    }
23
24
    public function getRepository($class): ObjectRepository
25
    {
26
        foreach ($this->managerRegistries as $managerRegistry) {
27
            if ($repository = $managerRegistry->getRepository($class)) {
28
                return $repository;
29
            }
30
        }
31
32
        throw new \LogicException("Cannot find repository for class $class");
33
    }
34
35
    public function getManagerForClass($class): ?ObjectManager
36
    {
37
        foreach ($this->managerRegistries as $managerRegistry) {
38
            if ($managerForClass = $managerRegistry->getManagerForClass($class)) {
39
                return $managerForClass;
40
            }
41
        }
42
43
        return null;
44
    }
45
46
    /** @return array<ObjectManager> */
47
    public function getManagers(): array
48
    {
49
        return array_reduce(
50
            $this->managerRegistries,
51
            static function (array $carry, ManagerRegistry $managerRegistry) {
52
                return array_merge($carry, $managerRegistry->getManagers());
53
            },
54
            []
55
        );
56
    }
57
}
58