Completed
Push — master ( c64d25...ac7c6c )
by Christopher
19:43 queued 17:08
created

DoormanConnector::pgsql()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 8
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 8
loc 8
ccs 0
cts 5
cp 0
rs 9.4286
cc 1
eloc 5
nc 1
nop 1
crap 2
1
<?php
2
3
namespace AsyncPHP\Icicle\Database\Connector;
4
5
use AsyncPHP\Doorman\Manager;
6
use AsyncPHP\Doorman\Manager\ProcessManager;
7
use AsyncPHP\Doorman\Task\ProcessCallbackTask;
8
use AsyncPHP\Icicle\Database\Connector;
9
use AsyncPHP\Remit\Client;
10
use AsyncPHP\Remit\Client\ZeroMqClient;
11
use AsyncPHP\Remit\Location\InMemoryLocation;
12
use AsyncPHP\Remit\Server;
13
use AsyncPHP\Remit\Server\ZeroMqServer;
14
use Aura\Sql\ExtendedPdo;
15
use Icicle\Loop;
16
use Icicle\Promise\Deferred;
17
use Icicle\Promise\PromiseInterface;
18
use InvalidArgumentException;
19
use PDO;
20
21
final class DoormanConnector implements Connector
22
{
23
    /**
24
     * @var int
25
     */
26
    private $id = 1;
27
28
    /**
29
     * @var array
30
     */
31
    private $deferred = [];
32
33
    /**
34
     * @var Manager
35
     */
36
    private $manager;
37
38
    /**
39
     * @var Server
40
     */
41
    private $server;
42
43
    /**
44
     * @var Client
45
     */
46
    private $client;
47
48
    /**
49
     * @inheritdoc
50
     *
51
     * @param array $config
52
     *
53
     * @return PromiseInterface
54
     *
55
     * @throws InvalidArgumentException
56
     */
57 1
    public function connect(array $config)
58
    {
59 1
        $this->manager = new ProcessManager();
60
61 1
        $this->validate($config);
62 1
        $this->connectRemit($config);
63 1
        $this->connectDoorman($config);
64
65
        $this->server->addListener("r", function ($result, $id) {
66 1
            if (isset($this->deferred[$id])) {
67 1
                $this->deferred[$id]->resolve($result);
68 1
                unset($this->deferred[$id]);
69 1
            }
70 1
        });
71
72
        $this->server->addListener("e", function ($error, $id) {
73
            if (isset($this->deferred[$id])) {
74
                $this->deferred[$id]->reject($error);
75
                unset($this->deferred[$id]);
76
            }
77 1
        });
78
79
        Loop\periodic(0, function () {
80 1
            $this->server->tick();
81 1
        });
82
83 1
        $this->manager->tick();
84 1
    }
85
86
    /**
87
     * @param array $config
88
     *
89
     * @throws InvalidArgumentException
90
     */
91 1
    private function validate(array $config)
92
    {
93 1
        if (!isset($config["remit"])) {
94
            throw new InvalidArgumentException("Undefined remit");
95
        }
96
97 1
        if (!isset($config["remit"]["driver"])) {
98
            throw new InvalidArgumentException("Undefined remit driver");
99
        }
100
101 1
        if (!isset($config["remit"]["server"])) {
102
            throw new InvalidArgumentException("Undefined remit server");
103
        }
104
105 1
        if (!isset($config["remit"]["client"])) {
106
            throw new InvalidArgumentException("Undefined remit client");
107
        }
108
109 1
        if ($config["remit"]["driver"] === "zeromq") {
110 1
            if (!isset($config["remit"]["server"]["port"])) {
111
                throw new InvalidArgumentException("Undefined remit server port");
112
            }
113
114 1
            if (!isset($config["remit"]["client"]["port"])) {
115
                throw new InvalidArgumentException("Undefined remit client port");
116
            }
117 1
        } else {
118
            throw new InvalidArgumentException("Unrecognised remit driver");
119
        }
120 1
    }
121
122
    /**
123
     * @param array $config
124
     */
125 1
    private function connectRemit(array $config)
126
    {
127 1
        $server = $config["remit"]["server"];
128 1
        $client = $config["remit"]["client"];
129
130 1
        if ($config["remit"]["driver"] === "zeromq") {
131 1
            $server = array_merge([
132 1
                "host" => "127.0.0.1",
133 1
            ], $server);
134
135 1
            $this->server = new ZeroMqServer(
136 1
                new InMemoryLocation(
137 1
                    $server["host"],
138 1
                    $server["port"]
139 1
                )
140 1
            );
141
142 1
            $client = array_merge([
143 1
                "host" => "127.0.0.1",
144 1
            ], $client);
145
146 1
            $this->client = new ZeroMqClient(
147 1
                new InMemoryLocation(
148 1
                    $client["host"],
149 1
                    $client["port"]
150 1
                )
151 1
            );
152 1
        }
153 1
    }
154
155
    /**
156
     * @param array $config
157
     */
158 1
    private function connectDoorman(array $config)
159
    {
160 1
        $server = $config["remit"]["server"];
161 1
        $client = $config["remit"]["client"];
162
163 1
        if ($config["remit"]["driver"] === "zeromq") {
164
            $task = new ProcessCallbackTask(function () use ($config, $server, $client) {
165
                $config = array_merge([
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $config, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
166
                    "host" => "127.0.0.1",
167
                    "port" => 3306,
168
                    "charset" => "utf8",
169
                    "socket" => null,
170
                ], $config);
171
172
                $server = array_merge([
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $server, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
173
                    "host" => "127.0.0.1",
174
                ], $server);
175
176
                $client = array_merge([
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $client, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
177
                    "host" => "127.0.0.1",
178
                ], $client);
179
180
                $remitServer = new ZeroMqServer(
181
                    new InMemoryLocation(
182
                        $client["host"],
183
                        $client["port"]
184
                    )
185
                );
186
187
                $remitClient = new ZeroMqClient(
188
                    new InMemoryLocation(
189
                        $server["host"],
190
                        $server["port"]
191
                    )
192
                );
193
194
                if ($config["driver"] === "mysql") {
195
                    $dsn = $this->mysql($config);
196
                }
197
198
                if ($config["driver"] === "pgsql") {
199
                    $dsn = $this->pgsql($config);
200
                }
201
202
                if ($config["driver"] === "sqlite") {
203
                    $dsn = $this->sqlite($config);
204
                    $config["username"] = null;
205
                    $config["password"] = null;
206
                }
207
208
                if ($config["driver"] === "sqlsrv") {
209
                    $dsn = $this->sqlsrv($config);
210
                }
211
212
                $connection = new ExtendedPdo(
213
                    new PDO($dsn, $config["username"], $config["password"])
0 ignored issues
show
Bug introduced by
The variable $dsn does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
214
                );
215
216
                $remitServer->addListener("q", function ($query, $values, $id) use ($remitClient, $connection) {
217
                    $remitClient->emit("r", [$connection->fetchAll($query, $values), $id]);
218
                });
219
220
                Loop\periodic(0, function () use ($remitServer) {
221
                    $remitServer->tick();
222
                });
223
224
                Loop\run();
225 1
            });
226
227 1
            $this->manager->addTask($task);
228 1
        }
229 1
    }
230
231
    /**
232
     * @param array $config
233
     *
234
     * @return string
235
     */
236
    private function mysql(array $config)
237
    {
238
        $host = (string) $config["host"];
239
        $port = (int) $config["port"];
240
        $database = (string) $config["database"];
241
        $socket = (string) $config["socket"];
242
        $charset = (string) $config["charset"];
243
244
        return "mysql:host={$host};port={$port};dbname={$database};unix_socket={$socket};charset={$charset}";
245
    }
246
247
    /**
248
     * @param array $config
249
     *
250
     * @return string
251
     */
252 View Code Duplication
    private function pgsql(array $config)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
253
    {
254
        $host = (string) $config["host"];
255
        $port = (int) $config["port"];
256
        $database = (string) $config["database"];
257
258
        return "pgsql:host={$host};port={$port};dbname={$database}";
259
    }
260
261
    /**
262
     * @param array $config
263
     *
264
     * @return string
265
     */
266
    private function sqlite(array $config)
267
    {
268
        $file = (string) $config["file"];
269
270
        return "sqlite:{$file}";
271
    }
272
273
    /**
274
     * @param array $config
275
     *
276
     * @return string
277
     */
278 View Code Duplication
    private function sqlsrv(array $config)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
279
    {
280
        $host = (string) $config["host"];
281
        $port = (int) $config["port"];
282
        $database = (string) $config["database"];
283
284
        return "sqlsrv:Server={$host},{$port};Database={$database}";
285
    }
286
287
    /**
288
     * @inheritdoc
289
     *
290
     * @param string $query
291
     * @param array $values
292
     *
293
     * @return PromiseInterface
294
     *
295
     * @throws InvalidArgumentException
296
     */
297 1
    public function query($query, $values)
298
    {
299 1
        $id = $this->id++;
300
301 1
        $deferred = new Deferred();
302
303 1
        $this->client->emit("q", [$query, $values, "d{$id}"]);
304
305 1
        $this->deferred["d{$id}"] = $deferred;
306
307 1
        return $deferred->getPromise();
308
    }
309
}
310