Completed
Pull Request — master (#5)
by Alessandro
03:18
created

ClientRegistry::getClient()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 4
nop 2
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Facile\MongoDbBundle\Services;
6
7
use Facile\MongoDbBundle\Capsule\Client;
8
use Facile\MongoDbBundle\Models\ConnectionConfiguration;
9
10
/**
11
 * Class ClientRegistry.
12
 */
13
class ClientRegistry
14
{
15
    /** @var Client[] */
16
    private $clients;
17
18
    /** @var ConnectionConfiguration[] */
19
    private $configurations;
20
21 2
    public function __construct()
22
    {
23 2
        $this->clients = [];
24 2
        $this->configurations = [];
25 2
    }
26
27
    /**
28
     * @param string $name
29
     * @param array  $conf
30
     */
31 2
    public function addClientConfiguration(string $name, array $conf)
32
    {
33 2
        $this->configurations[$name] = new ConnectionConfiguration($conf['host'], $conf['port'], $conf['username'], $conf['password']);
34 2
    }
35
36
    /**
37
     * @param string $name
38
     * @param string $databaseName
39
     *
40
     * @return Client
41
     */
42 2
    public function getClient(string $name, string $databaseName = null): Client
43
    {
44 2
        $clientKey = !is_null($databaseName) ? $name.'.'.$databaseName : $name;
45
46 2
        if (!isset($this->clients[$clientKey])) {
47 2
            $conf = $this->configurations[$name];
48 2
            $this->clients[$clientKey] = new Client($conf->getConnectionUri($databaseName));
49
        }
50
51 2
        return $this->clients[$clientKey];
52
    }
53
54
    /**
55
     * @param string $name
56
     * @param string $databaseName
57
     *
58
     * @return Client
59
     */
60 2
    public function getClientForDatabase(string $name, string $databaseName): Client
61
    {
62 2
        return $this->getClient($name, $databaseName);
63
    }
64
}
65