Passed
Pull Request — master (#63)
by Eugene
03:00
created

ClientBuilder::createPacker()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 5
nc 5
nop 0
dl 0
loc 11
rs 9.6111
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of the Tarantool Client package.
5
 *
6
 * (c) Eugene Leonovich <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Tarantool\Client\Tests\Integration;
15
16
use Tarantool\Client\Client;
17
use Tarantool\Client\Connection\Connection;
18
use Tarantool\Client\Connection\StreamConnection;
19
use Tarantool\Client\Handler\DefaultHandler;
20
use Tarantool\Client\Handler\MiddlewareHandler;
21
use Tarantool\Client\Middleware\AuthenticationMiddleware;
22
use Tarantool\Client\Middleware\RetryMiddleware;
23
use Tarantool\Client\Packer\Packer;
24
use Tarantool\Client\Packer\PeclPacker;
25
use Tarantool\Client\Packer\PurePacker;
26
27
final class ClientBuilder
28
{
29
    private const PACKER_PURE = 'pure';
30
    private const PACKER_PECL = 'pecl';
31
32
    private const DEFAULT_TCP_HOST = '127.0.0.1';
33
    private const DEFAULT_TCP_PORT = 3301;
34
35
    private $packer;
36
    private $packerPureFactory;
37
    private $packerPeclFactory;
38
    private $uri;
39
    private $options = [];
40
    private $connectionOptions = [];
41
42
    public function setPacker(string $packer) : self
43
    {
44
        $this->packer = $packer;
45
46
        return $this;
47
    }
48
49
    public function setPackerPureFactory(\Closure $factory) : self
50
    {
51
        $this->packerPureFactory = $factory;
52
53
        return $this;
54
    }
55
56
    public function setPackerPeclFactory(\Closure $factory) : self
57
    {
58
        $this->packerPeclFactory = $factory;
59
60
        return $this;
61
    }
62
63
    public function setOptions(array $options) : self
64
    {
65
        $this->options = $options;
66
67
        return $this;
68
    }
69
70
    public function setConnectionOptions(array $options) : self
71
    {
72
        $this->connectionOptions = $options;
73
74
        return $this;
75
    }
76
77
    public function isTcpConnection() : bool
78
    {
79
        return 0 === strpos($this->uri, 'tcp:');
80
    }
81
82
    public function setHost(string $host) : self
83
    {
84
        $port = parse_url($this->uri, PHP_URL_PORT);
85
        $this->uri = sprintf('tcp://%s:%d', $host, $port ?: self::DEFAULT_TCP_PORT);
86
87
        return $this;
88
    }
89
90
    public function setPort(int $port) : self
91
    {
92
        $host = parse_url($this->uri, PHP_URL_HOST);
93
        $this->uri = sprintf('tcp://%s:%d', $host ?: self::DEFAULT_TCP_HOST, $port);
94
95
        return $this;
96
    }
97
98
    public function setUri(string $uri) : self
99
    {
100
        if (0 === strpos($uri, '/')) {
101
            $uri = 'unix://'.$uri;
102
        }
103
104
        $this->uri = $uri;
105
106
        return $this;
107
    }
108
109
    public function getUri() : string
110
    {
111
        return $this->uri;
112
    }
113
114
    public function build() : Client
115
    {
116
        $connection = $this->createConnection();
117
        $packer = $this->createPacker();
118
        $handler = new DefaultHandler($connection, $packer);
119
120
        if (isset($this->options['max_retries'])) {
121
            $handler = MiddlewareHandler::create($handler, RetryMiddleware::linear($this->options['max_retries']));
122
        }
123
        if (isset($this->options['username'])) {
124
            $handler = MiddlewareHandler::create($handler, new AuthenticationMiddleware($this->options['username'], $this->options['password'] ?? ''));
125
        }
126
127
        return new Client($handler);
128
    }
129
130
    public static function createFromEnv() : self
131
    {
132
        return (new self())
133
            ->setPacker(getenv('TNT_PACKER'))
134
            ->setUri(getenv('TNT_CONN_URI'));
135
    }
136
137
    public static function createFromEnvForTheFakeServer() : self
138
    {
139
        $builder = self::createFromEnv();
140
141
        if ($builder->isTcpConnection()) {
142
            $builder->setHost('0.0.0.0');
143
            $builder->setPort(self::findOpenTcpPort(8000));
144
        } else {
145
            $builder->setUri(sprintf('unix://%s/tnt_client_%s.sock', sys_get_temp_dir(), bin2hex(random_bytes(10))));
146
        }
147
148
        return $builder;
149
    }
150
151
    public function createConnection() : Connection
152
    {
153
        if (!$this->uri) {
154
            throw new \LogicException('Connection URI is not set.');
155
        }
156
157
        return StreamConnection::create($this->uri, $this->connectionOptions);
158
    }
159
160
    public function createPacker() : Packer
161
    {
162
        if (self::PACKER_PURE === $this->packer) {
163
            return $this->packerPureFactory ? ($this->packerPureFactory)() : new PurePacker();
164
        }
165
166
        if (self::PACKER_PECL === $this->packer) {
167
            return $this->packerPeclFactory ? ($this->packerPeclFactory)() : new PeclPacker();
168
        }
169
170
        throw new \UnexpectedValueException(sprintf('"%s" packer is not supported.', $this->packer));
171
    }
172
173
    private static function findOpenTcpPort(int $min) : int
174
    {
175
        $maxTries = 10;
176
        $try = 0;
177
178
        while (true) {
179
            $port = $min + $try * 500 + random_int(1, 500);
180
            if (!$fp = @stream_socket_client("tcp://127.0.0.1:$port", $errorCode, $errorMessage, 1)) {
181
                return $port;
182
            }
183
184
            fclose($fp);
185
186
            if (++$try === $maxTries) {
187
                throw new \RuntimeException('Failed to find open tcp port.');
188
            }
189
        }
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return integer. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
190
    }
191
}
192