MongoDbStorageDriverFactory   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 0
loc 67
c 0
b 0
f 0
wmc 5
lcom 1
cbo 1
ccs 0
cts 28
cp 0
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getDns2client() 0 4 1
A create() 0 7 1
A getOrCreateClient() 0 16 2
1
<?php
2
/**
3
 * Created by IntelliJ IDEA.
4
 * User: gerk
5
 * Date: 12.04.17
6
 * Time: 06:26
7
 */
8
9
namespace PeekAndPoke\Component\Slumber\Data\MongoDb;
10
11
use MongoDB\Client;
12
use PeekAndPoke\Component\Slumber\Data\EntityPool;
13
use PeekAndPoke\Component\Slumber\Data\StorageDriver;
14
use PeekAndPoke\Component\Slumber\Data\StorageDriverFactory;
15
16
17
/**
18
 * @author Karsten J. Gerber <[email protected]>
19
 */
20
class MongoDbStorageDriverFactory implements StorageDriverFactory
21
{
22
    /** @var EntityPool */
23
    private $entityPool;
24
    /** @var MongoDbCodecSet */
25
    private $codecSet;
26
27
    /** @var Client[] Key is the dns, value is the Client */
28
    private $dns2client = [];
29
30
    /**
31
     * MongoDbStorageDriverFactory constructor.
32
     *
33
     * @param EntityPool      $entityPool
34
     * @param MongoDbCodecSet $codecSet
35
     */
36
    public function __construct(EntityPool $entityPool, MongoDbCodecSet $codecSet)
37
    {
38
        $this->entityPool = $entityPool;
39
        $this->codecSet   = $codecSet;
40
    }
41
42
    /**
43
     * @return Client[]
44
     */
45
    public function getDns2client()
46
    {
47
        return $this->dns2client;
48
    }
49
50
    /**
51
     * @param array            $config
52
     * @param string           $tableName
53
     * @param \ReflectionClass $baseClass
54
     *
55
     * @return StorageDriver|MongoDbStorageDriver
56
     */
57
    public function create($config, $tableName, \ReflectionClass $baseClass)
58
    {
59
        $client = $this->getOrCreateClient($config['dns']);
60
        $table  = $client->selectCollection($config['database'], $tableName);
61
62
        return new MongoDbStorageDriver($this->entityPool, $this->codecSet, $table, $baseClass);
63
    }
64
65
    /**
66
     * @param string $dns
67
     *
68
     * @return Client
69
     */
70
    private function getOrCreateClient($dns)
71
    {
72
        if (isset($this->dns2client[$dns])) {
73
            return $this->dns2client[$dns];
74
        }
75
76
        return $this->dns2client[$dns] = new Client(
77
            $dns,
78
            [
79
                // do not connect right away
80
                'connect' => false,
81
                // force return of associative array
82
                'typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array'],
83
            ]
84
        );
85
    }
86
}
87