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