DoctrineDbalConnectionRegistry::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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