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

ConnectionFactory   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
c 0
b 0
f 0
lcom 1
cbo 3
dl 0
loc 56
ccs 14
cts 14
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A createConnection() 0 6 1
A createClient() 0 4 1
A getClientForConfiguration() 0 11 2
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