Completed
Pull Request — master (#2)
by Alessandro
02:37
created

ConnectionFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Facile\MongoDbBundle\Services;
6
7
use Facile\MongoDbBundle\Models\ConnectionConfiguration;
8
use MongoDB\Client;
9
use MongoDB\Database;
10
11
/**
12
 * Class ConnectionFactory.
13
 */
14
final class ConnectionFactory
15
{
16
    /** @var ConnectionRegistry */
17
    private $registry;
18
19
    /**
20
     * ConnectionFactory constructor.
21
     *
22
     * @param ConnectionRegistry $registry
23
     */
24 2
    public function __construct(ConnectionRegistry $registry)
25
    {
26 2
        $this->registry = $registry;
27 2
    }
28
29
    /**
30
     * @param ConnectionConfiguration $configuration
31
     * @param string                  $connectionKey
32
     *
33
     * @return Database
34
     */
35 2
    public function createConnection(ConnectionConfiguration $configuration, string $connectionKey): Database
36
    {
37 2
        $client = $this->getClientForConfiguration($configuration, $connectionKey);
38
39 2
        return $client->selectDatabase($configuration->getDatabase());
40
    }
41
42
    /**
43
     * @param ConnectionConfiguration $configuration
44
     *
45
     * @return Client
46
     */
47 2
    private function createClient(ConnectionConfiguration $configuration): Client
48
    {
49 2
        return new Client($configuration->getConnectionUri());
50
    }
51
52
    /**
53
     * @param ConnectionConfiguration $configuration
54
     * @param string                  $clientKey
55
     *
56
     * @return Client
57
     */
58 2
    private function getClientForConfiguration(ConnectionConfiguration $configuration, string $clientKey): Client
59
    {
60 2
        if (!$this->registry->hasClient($clientKey)) {
61 2
            $client = $this->createClient($configuration);
62 2
            $this->registry->addClient($clientKey, $client);
63
64 2
            return $client;
65
        }
66
67 1
        return $this->registry->getClient($clientKey);
68
    }
69
}
70