EntityManagerCollection::get()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
nc 2
nop 1
dl 0
loc 8
c 0
b 0
f 0
cc 2
rs 10
1
<?php
2
3
/**
4
 * This file is part of orm
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace Slick\Orm\Infrastructure\Persistence;
13
14
use ArrayIterator;
15
use Countable;
16
use Doctrine\ORM\EntityManagerInterface;
17
use IteratorAggregate;
18
use Slick\Orm\Infrastructure\Exception\UnknownEntityManagerException;
19
20
/**
21
 * EntityManagerCollection
22
 *
23
 * @package Slick\Orm\Infrastructure\Persistence
24
 * @implements IteratorAggregate<string, EntityManagerInterface>
25
 */
26
final class EntityManagerCollection implements Countable, IteratorAggregate
27
{
28
    /** @var array<string, EntityManagerInterface>  */
29
    private array $entityManagers = [];
30
31
    /**
32
     * Counts the number of entities in the collection.
33
     *
34
     * @return int The number of entities in the collection.
35
     */
36
    public function count(): int
37
    {
38
        return count($this->entityManagers);
39
    }
40
41
    /**
42
     * Retrieves an iterator for the entities array.
43
     *
44
     * @return ArrayIterator<string,EntityManagerInterface> The iterator for the entities array.
45
     */
46
    public function getIterator(): ArrayIterator
47
    {
48
        return new ArrayIterator($this->entityManagers);
49
    }
50
51
    /**
52
     * Adds an instance of EntityManagerInterface to the collection.
53
     *
54
     * @param string $name The name of the entity manager.
55
     * @param EntityManagerInterface $entityManager The entity manager instance to add.
56
     * @return EntityManagerCollection The updated entity manager collection.
57
     */
58
    public function add(string $name, EntityManagerInterface $entityManager): EntityManagerCollection
59
    {
60
        $this->entityManagers[$name] = $entityManager;
61
        return $this;
62
    }
63
64
    public function get(string $name): EntityManagerInterface
65
    {
66
        if (!isset($this->entityManagers[$name])) {
67
            throw new UnknownEntityManagerException(
68
                "There are no registered entity manager for '$name'"
69
            );
70
        }
71
        return $this->entityManagers[$name];
72
    }
73
}
74