Completed
Push — master ( 50addd...172cd1 )
by Sullivan
9s
created

ConnectionRegistry::addConnection()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
cc 2
eloc 4
nc 2
nop 3
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Algatux\InfluxDbBundle\Services;
6
7
use Algatux\InfluxDbBundle\Exception\ConnectionNotFoundException;
8
use InfluxDB\Database;
9
10
/**
11
 * Registry of all Database instances.
12
 */
13
final class ConnectionRegistry
14
{
15
    /**
16
     * @var Database[]
17
     */
18
    private $connections = [];
19
20
    /**
21
     * @var string
22
     */
23
    private $defaultConnectionName;
24
25
    /**
26
     * @param string $defaultConnectionName
27
     */
28 7
    public function __construct($defaultConnectionName)
29
    {
30 7
        $this->defaultConnectionName = $defaultConnectionName;
31 7
    }
32
33
    /**
34
     * @param string   $name
35
     * @param string   $protocol
36
     * @param Database $connection
37
     */
38 7
    public function addConnection(string $name, string $protocol, Database $connection)
39
    {
40 7
        if (!isset($this->connections[$name])) {
41 7
            $this->connections[$name] = [];
42
        }
43
44 7
        $this->connections[$name][$protocol] = $connection;
45 7
    }
46
47
    /**
48
     * @param string $name
49
     *
50
     * @return Database
51
     */
52 5
    public function getHttpConnection(string $name)
53
    {
54 5
        return $this->getConnection($name, 'http');
55
    }
56
57
    /**
58
     * @param string $name
59
     *
60
     * @return Database
61
     */
62 1
    public function getUdpConnection(string $name)
63
    {
64 1
        return $this->getConnection($name, 'udp');
65
    }
66
67
    /**
68
     * @return Database
69
     */
70 3
    public function getDefaultHttpConnection()
71
    {
72 3
        return $this->getConnection($this->defaultConnectionName, 'http');
73
    }
74
75
    /**
76
     * @return Database
77
     */
78 1
    public function getDefaultUdpConnection()
79
    {
80 1
        return $this->getConnection($this->defaultConnectionName, 'udp');
81
    }
82
83
    /**
84
     * @param string $name
85
     * @param string $protocol
86
     *
87
     * @return Database
88
     *
89
     * @throws ConnectionNotFoundException
90
     */
91 7
    private function getConnection(string $name, string $protocol)
92
    {
93 7
        if (!isset($this->connections[$name][$protocol])) {
94 1
            throw new ConnectionNotFoundException($name, $protocol);
95
        }
96
97 6
        return $this->connections[$name][$protocol];
98
    }
99
}
100