1 | <?php |
||
2 | declare(strict_types = 1); |
||
3 | |||
4 | namespace TBolier\RethinkQL\Connection; |
||
5 | |||
6 | use Symfony\Component\Serializer\Encoder\JsonEncoder; |
||
7 | use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; |
||
8 | use Symfony\Component\Serializer\Serializer; |
||
9 | use TBolier\RethinkQL\Connection\Socket\Socket; |
||
10 | use TBolier\RethinkQL\Connection\Socket\Handshake; |
||
11 | use TBolier\RethinkQL\Serializer\QueryNormalizer; |
||
12 | use TBolier\RethinkQL\Types\VersionDummy\Version; |
||
13 | |||
14 | class Registry implements RegistryInterface |
||
15 | { |
||
16 | /** |
||
17 | * @var ConnectionInterface[] |
||
18 | */ |
||
19 | private $connections; |
||
20 | |||
21 | /** |
||
22 | * @param array|null $connections |
||
23 | * @throws ConnectionException |
||
24 | */ |
||
25 | public function __construct(array $connections = null) |
||
26 | { |
||
27 | if ($connections) { |
||
28 | foreach ($connections as $name => $options) { |
||
29 | if (!$options instanceof OptionsInterface) { |
||
30 | continue; |
||
31 | } |
||
32 | |||
33 | $this->addConnection($name, $options); |
||
34 | } |
||
35 | } |
||
36 | } |
||
37 | |||
38 | /** |
||
39 | * @inheritdoc |
||
40 | * @throws ConnectionException |
||
41 | */ |
||
42 | public function addConnection(string $name, OptionsInterface $options): bool |
||
43 | { |
||
44 | if ($this->hasConnection($name)) { |
||
45 | throw new ConnectionException("The connection {$name} has already been added.", 400); |
||
46 | } |
||
47 | |||
48 | // TODO: Create factory for instantiation Connection. |
||
49 | $this->connections[$name] = new Connection( |
||
50 | function() use ($options) { |
||
0 ignored issues
–
show
Coding Style
introduced
by
![]() |
|||
51 | return new Socket( |
||
52 | $options |
||
53 | ); |
||
54 | }, |
||
55 | new Handshake($options->getUser(), $options->getPassword(), Version::V1_0), |
||
56 | $options->getDbName(), |
||
57 | new Serializer( |
||
58 | [new QueryNormalizer()], |
||
59 | [new JsonEncoder()] |
||
60 | ), |
||
61 | new Serializer( |
||
62 | [new ObjectNormalizer()], |
||
63 | [new JsonEncoder()] |
||
64 | ) |
||
65 | ); |
||
66 | |||
67 | return true; |
||
68 | } |
||
69 | |||
70 | /** |
||
71 | * @inheritdoc |
||
72 | */ |
||
73 | public function hasConnection(string $name): bool |
||
74 | { |
||
75 | return isset($this->connections[$name]); |
||
76 | } |
||
77 | |||
78 | /** |
||
79 | * @inheritdoc |
||
80 | * @throws ConnectionException |
||
81 | */ |
||
82 | public function getConnection(string $name): ConnectionInterface |
||
83 | { |
||
84 | if (!$this->connections[$name]) { |
||
85 | throw new ConnectionException("The connection {$name} does not exist.", 400); |
||
86 | } |
||
87 | |||
88 | return $this->connections[$name]; |
||
89 | } |
||
90 | } |
||
91 |