Completed
Push — master ( 61c032...c23418 )
by Alessandro
03:27
created

ConnectionFactory   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
c 1
b 0
f 0
lcom 1
cbo 2
dl 0
loc 52
ccs 18
cts 18
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A createClient() 0 10 2
B createConnection() 0 22 5
1
<?php
2
3
namespace Algatux\InfluxDbBundle\Services;
4
5
use InfluxDB\Client;
6
use InfluxDB\Driver\UDP;
7
8
/**
9
 * Create connections as `InfluxDB\Database` instances.
10
 *
11
 * This keeps clients on a property to avoid useless instance duplication.
12
 *
13
 * @internal
14
 */
15
final class ConnectionFactory
16
{
17
    /**
18
     * @var Client[]
19
     */
20
    private $clients = [];
21
22
    /**
23
     * @param string $database
24
     * @param string $host
25
     * @param int    $httpPort
26
     * @param int    $udpPort
27
     * @param string $user
28
     * @param string $password
29
     * @param bool   $udp
30
     *
31
     * @return \InfluxDB\Database
32
     */
33 2
    public function createConnection(string $database, string $host, int $httpPort, int $udpPort, string $user, string $password, bool $udp = false)
34
    {
35 2
        $protocol = $udp ? 'udp' : 'http';
36
        // Define the client key to retrieve or create the client instance.
37 2
        $clientKey = sprintf('%s.%s.%s', $host, $udpPort, $httpPort);
38 2
        if (!empty($user)) {
39 1
            $clientKey .= '.'.$user;
40
        }
41 2
        if (!empty($password)) {
42 1
            $clientKey .= '.'.$password;
43
        }
44 2
        $clientKey .= '.'.$protocol;
45
46 2
        if (!array_key_exists($clientKey, $this->clients)) {
47 2
            $client = $this->createClient($host, $httpPort, $udpPort, $user, $password, $udp);
48 2
            $this->clients[$clientKey] = $client;
49
        } else {
50 1
            $client = $this->clients[$clientKey];
51
        }
52
53 2
        return $client->selectDB($database);
54
    }
55
56 2
    private function createClient(string $host, int $httpPort, int $udpPort, string $user, string $password, bool $udp = false)
57
    {
58 2
        $client = new Client($host, $httpPort, $user, $password);
59
60 2
        if ($udp) {
61 2
            $client->setDriver(new UDP($client->getHost(), $udpPort));
62
        }
63
64 2
        return $client;
65
    }
66
}
67