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
|
|
|
/** @var ClientUriBuilder */ |
20
|
|
|
private $uriBuilder; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* ClientRegistry constructor. |
24
|
|
|
* |
25
|
|
|
* @param ClientUriBuilder $uriBuilder |
26
|
|
|
*/ |
27
|
2 |
|
public function __construct(ClientUriBuilder $uriBuilder) |
28
|
|
|
{ |
29
|
2 |
|
$this->clients = []; |
30
|
2 |
|
$this->configurations = []; |
31
|
2 |
|
$this->uriBuilder = $uriBuilder; |
32
|
2 |
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param string $name |
36
|
|
|
* @param array $conf |
37
|
|
|
*/ |
38
|
2 |
|
public function addClientConfiguration(string $name, array $conf) |
39
|
|
|
{ |
40
|
2 |
|
$this->configurations[$name] = new ClientConfiguration($conf['host'], $conf['port'], $conf['username'], $conf['password']); |
41
|
2 |
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param string $name |
45
|
|
|
* @param string $databaseName |
46
|
|
|
* |
47
|
|
|
* @return Client |
48
|
|
|
*/ |
49
|
2 |
|
public function getClient(string $name, string $databaseName = null): Client |
50
|
|
|
{ |
51
|
2 |
|
$clientKey = !is_null($databaseName) ? $name.'.'.$databaseName : $name; |
52
|
|
|
|
53
|
2 |
|
if (!isset($this->clients[$clientKey])) { |
54
|
2 |
|
$conf = $this->configurations[$name]; |
55
|
2 |
|
$uri = $this->uriBuilder->buildUriForConfiguration($conf, $databaseName); |
56
|
2 |
|
$this->clients[$clientKey] = new Client($uri); |
57
|
|
|
} |
58
|
|
|
|
59
|
2 |
|
return $this->clients[$clientKey]; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param string $name |
64
|
|
|
* @param string $databaseName |
65
|
|
|
* |
66
|
|
|
* @return Client |
67
|
|
|
*/ |
68
|
2 |
|
public function getClientForDatabase(string $name, string $databaseName): Client |
69
|
|
|
{ |
70
|
2 |
|
return $this->getClient($name, $databaseName); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|