Completed
Pull Request — master (#5)
by Alessandro
02:27
created

ClientRegistry::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
crap 1
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\ClientConfiguration;
9
10
/**
11
 * Class ClientRegistry.
12
 */
13
class ClientRegistry
14
{
15
    /** @var Client[] */
16
    private $clients;
17
    /** @var ClientConfiguration[] */
18
    private $configurations;
19
20
    /**
21
     * ClientRegistry constructor.
22
     */
23 2
    public function __construct()
24
    {
25 2
        $this->clients = [];
26 2
        $this->configurations = [];
27 2
    }
28
29
    /**
30
     * @param string $name
31
     * @param array  $conf
32
     */
33 2
    public function addClientConfiguration(string $name, array $conf)
34
    {
35 2
        $this->configurations[$name] = new ClientConfiguration(
36 2
            $conf['host'],
37 2
            $conf['port'],
38 2
            $conf['username'],
39 2
            $conf['password']
40
        );
41 2
    }
42
43
    /**
44
     * @param string $name
45
     * @param string $databaseName
46
     *
47
     * @return Client
48
     */
49 2
    public function getClientForDatabase(string $name, string $databaseName): Client
50
    {
51 2
        return $this->getClient($name, $databaseName);
52
    }
53
54
    /**
55
     * @param string $name
56
     * @param string $databaseName
57
     *
58
     * @return Client
59
     */
60 2
    public function getClient(string $name, string $databaseName = null): Client
61
    {
62 2
        $clientKey = !is_null($databaseName) ? $name.'.'.$databaseName : $name;
63
64 2
        if (!isset($this->clients[$clientKey])) {
65 2
            $conf = $this->configurations[$name];
66 2
            $uri = sprintf('mongodb://%s:%d', $conf->getHost(), $conf->getPort());
67 2
            $options = array_merge($conf->getCredentialsArray(), ['db' => $databaseName]);
68 2
            $this->clients[$clientKey] = new Client($uri, $options);
69
        }
70
71 2
        return $this->clients[$clientKey];
72
    }
73
}
74