Failed Conditions
Pull Request — master (#31)
by Marc
03:33
created

src/Connection/Registry.php (1 issue)

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 3
    public function __construct(array $connections = null)
26
    {
27 3
        if ($connections) {
28 2
            foreach ($connections as $name => $options) {
29 2
                if (!$options instanceof OptionsInterface) {
30 1
                    continue;
31
                }
32
33 2
                $this->addConnection($name, $options);
34
            }
35
        }
36 3
    }
37
38
    /**
39
     * @inheritdoc
40
     * @throws ConnectionException
41
     */
42 2
    public function addConnection(string $name, OptionsInterface $options): bool
43
    {
44 2
        if ($this->hasConnection($name)) {
45 1
            throw new ConnectionException("The connection {$name} has already been added.", 400);
46
        }
47
48
        // TODO: Create factory for instantiation Connection.
49 2
        $this->connections[$name] = new Connection(
50 2
            function() use ($options) {
0 ignored issues
show
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
51
                return new Socket(
52
                    $options
53
                );
54 2
            },
55 2
            new Handshake($options->getUser(), $options->getPassword(), Version::V1_0),
56 2
            $options->getDbName(),
57 2
            new Serializer(
58 2
                [new QueryNormalizer()],
59 2
                [new JsonEncoder()]
60
            ),
61 2
            new Serializer(
62 2
                [new ObjectNormalizer()],
63 2
                [new JsonEncoder()]
64
            )
65
        );
66
67 2
        return true;
68
    }
69
70
    /**
71
     * @inheritdoc
72
     */
73 2
    public function hasConnection(string $name): bool
74
    {
75 2
        return isset($this->connections[$name]);
76
    }
77
78
    /**
79
     * @inheritdoc
80
     * @throws ConnectionException
81
     */
82 2
    public function getConnection(string $name): ConnectionInterface
83
    {
84 2
        if (!$this->connections[$name]) {
85 1
            throw new ConnectionException("The connection {$name} does not exist.", 400);
86
        }
87
88 1
        return $this->connections[$name];
89
    }
90
}
91