Completed
Pull Request — master (#37)
by Eugene
05:31
created

StreamConnection   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 81
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 92.11%

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 3
dl 0
loc 81
ccs 35
cts 38
cp 0.9211
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 2
A isClosed() 0 4 1
A open() 0 24 2
A send() 0 11 2
A read() 0 9 3
A close() 0 7 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Tarantool Client package.
7
 *
8
 * (c) Eugene Leonovich <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Tarantool\Client\Connection;
15
16
use Tarantool\Client\Exception\CommunicationFailed;
17
use Tarantool\Client\Exception\ConnectionFailed;
18
use Tarantool\Client\IProto;
19
use Tarantool\Client\Packer\PackUtils;
20
21
final class StreamConnection implements Connection
22
{
23
    public const DEFAULT_URI = 'tcp://127.0.0.1:3301';
24
25
    private $stream;
26
    private $uri;
27
    private $options = [
28
        'connect_timeout' => 5,
29
        'socket_timeout' => 5,
30
        'tcp_nodelay' => true,
31
    ];
32
33 52
    public function __construct(string $uri = self::DEFAULT_URI, array $options = [])
34
    {
35 52
        $this->uri = $uri;
36
37 52
        if ($options) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $options of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
38 4
            $this->options = $options + $this->options;
39
        }
40 52
    }
41
42 52
    public function open() : string
43
    {
44 52
        $this->close();
45
46 52
        $stream = @\stream_socket_client(
47 52
            $this->uri,
48 52
            $errorCode,
49 52
            $errorMessage,
50 52
            (float) $this->options['connect_timeout'],
51 52
            \STREAM_CLIENT_CONNECT,
52 52
            \stream_context_create(['socket' => ['tcp_nodelay' => (bool) $this->options['tcp_nodelay']]])
53
        );
54
55 52
        if (false === $stream) {
56 12
            throw ConnectionFailed::fromUriAndReason($this->uri, $errorMessage);
57
        }
58
59 40
        $this->stream = $stream;
60 40
        \stream_set_timeout($this->stream, $this->options['socket_timeout']);
61
62 40
        $greeting = $this->read(IProto::GREETING_SIZE, 'Unable to read greeting.');
63
64 36
        return IProto::parseGreeting($greeting);
65
    }
66
67 52
    public function close() : void
68
    {
69 52
        if ($this->stream) {
70
            \fclose($this->stream);
71
            $this->stream = null;
72
        }
73 52
    }
74
75 52
    public function isClosed() : bool
76
    {
77 52
        return !\is_resource($this->stream);
78
    }
79
80 6
    public function send(string $data) : string
81
    {
82 6
        if (!\fwrite($this->stream, $data)) {
83
            throw new CommunicationFailed('Unable to write request.');
84
        }
85
86 6
        $length = $this->read(IProto::LENGTH_SIZE, 'Unable to read response length.');
87 2
        $length = PackUtils::unpackLength($length);
88
89 2
        return $this->read($length, 'Unable to read response.');
90
    }
91
92 40
    private function read(int $length, string $errorMessage) : string
93
    {
94 40
        if ($data = \stream_get_contents($this->stream, $length)) {
95 36
            return $data;
96
        }
97
98 10
        $meta = \stream_get_meta_data($this->stream);
99 10
        throw new CommunicationFailed($meta['timed_out'] ? 'Read timed out.' : $errorMessage);
100
    }
101
}
102