DoctrineDbalConnectionRegistry::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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