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] = $this->buildClientConfiguration($conf); |
36
|
2 |
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param string $name |
40
|
|
|
* @param string $databaseName |
41
|
|
|
* |
42
|
|
|
* @return Client |
43
|
|
|
*/ |
44
|
2 |
|
public function getClientForDatabase(string $name, string $databaseName): Client |
45
|
|
|
{ |
46
|
2 |
|
return $this->getClient($name, $databaseName); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param string $name |
51
|
|
|
* @param string $databaseName |
52
|
|
|
* |
53
|
|
|
* @return Client |
54
|
|
|
*/ |
55
|
2 |
|
public function getClient(string $name, string $databaseName = null): Client |
56
|
|
|
{ |
57
|
2 |
|
$clientKey = !is_null($databaseName) ? $name.'.'.$databaseName : $name; |
58
|
|
|
|
59
|
2 |
|
if (!isset($this->clients[$clientKey])) { |
60
|
2 |
|
$conf = $this->configurations[$name]; |
61
|
2 |
|
$uri = sprintf('mongodb://%s:%d', $conf->getHost(), $conf->getPort()); |
62
|
2 |
|
$options = array_merge(['db' => $databaseName], $conf->getOptions()); |
63
|
2 |
|
$this->clients[$clientKey] = new Client($uri, $options); |
64
|
|
|
} |
65
|
|
|
|
66
|
2 |
|
return $this->clients[$clientKey]; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @param array $conf |
71
|
|
|
* |
72
|
|
|
* @return ClientConfiguration |
73
|
|
|
*/ |
74
|
2 |
|
private function buildClientConfiguration(array $conf): ClientConfiguration |
75
|
|
|
{ |
76
|
2 |
|
return new ClientConfiguration( |
77
|
2 |
|
$conf['host'], |
78
|
2 |
|
$conf['port'], |
79
|
2 |
|
$conf['username'], |
80
|
2 |
|
$conf['password'], |
81
|
|
|
[ |
82
|
2 |
|
'replicaSet' => $conf['replicaSet'], |
83
|
2 |
|
'ssl' => $conf['ssl'], |
84
|
2 |
|
'connectTimeoutMS' => $conf['connectTimeoutMS'], |
85
|
|
|
] |
86
|
|
|
); |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|