Test Failed
Pull Request — master (#2)
by Dominik
02:37
created

getConnections()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 13
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\DoctrineDbServiceProvider\Registry;
6
7
use Doctrine\Common\Persistence\ConnectionRegistry;
8
use Doctrine\DBAL\Connection;
9
use Psr\Container\ContainerInterface;
10
11
final class DoctrineDbalPsrConnectionRegistry implements ConnectionRegistry
12
{
13
    /**
14
     * @var ContainerInterface
15
     */
16
    private $container;
17
18
    /**
19
     * @var array<int, string>
20
     */
21
    private $connectionNames;
22
23
    /**
24
     * @var ContainerInterface
25
     */
26
    private $connections;
27
28
    /**
29
     * @var string
30
     */
31
    private $defaultConnectionName;
32
33
    public function __construct(ContainerInterface $container, array $connectionNames)
34
    {
35
        $this->container = $container;
36
        $this->connectionNames = $connectionNames;
37
    }
38
39
    public function getDefaultConnectionName(): string
40
    {
41
        $this->loadConnections();
42
43
        return $this->defaultConnectionName;
44
    }
45
46
    /**
47
     * @param string|null $name
48
     *
49
     * @throws \InvalidArgumentException
50
     */
51
    public function getConnection($name = null): Connection
52
    {
53
        $this->loadConnections();
54
55
        $name = $name ?? $this->getDefaultConnectionName();
56
57
        if (!$this->connections->has($name)) {
58
            throw new \InvalidArgumentException(sprintf('Missing connection with name "%s".', $name));
59
        }
60
61
        return $this->connections->get($name);
62
    }
63
64
    /**
65
     * @return array<string, Connection>
66
     */
67
    public function getConnections(): array
68
    {
69
        $this->loadConnections();
70
71
        $connections = [];
72
        /** @var string $name */
73
        foreach ($this->connectionNames as $name) {
74
            /** @var Connection $connection */
75
            $connection = $this->connections->get($name);
76
            $connections[$name] = $connection;
77
        }
78
79
        return $connections;
80
    }
81
82
    /**
83
     * @return array<string>
84
     */
85
    public function getConnectionNames(): array
86
    {
87
        return $this->connectionNames;
88
    }
89
90
    private function loadConnections(): void
91
    {
92
        if (null === $this->connections) {
93
            $this->connections = $this->container->get('doctrine.dbal.dbs');
94
            $this->defaultConnectionName = $this->container->get('doctrine.dbal.dbs.default');
95
        }
96
    }
97
}
98