1 | <?php |
||
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 | 258 | public function __construct(string $uri = self::DEFAULT_URI, array $options = []) |
|
41 | |||
42 | 258 | public function open() : string |
|
43 | { |
||
44 | 258 | $this->close(); |
|
45 | |||
46 | 258 | $stream = @\stream_socket_client( |
|
47 | 258 | $this->uri, |
|
48 | 258 | $errorCode, |
|
49 | 258 | $errorMessage, |
|
50 | 258 | (float) $this->options['connect_timeout'], |
|
51 | 258 | \STREAM_CLIENT_CONNECT, |
|
52 | 258 | \stream_context_create(['socket' => ['tcp_nodelay' => (bool) $this->options['tcp_nodelay']]]) |
|
53 | ); |
||
54 | |||
55 | 258 | if (false === $stream) { |
|
56 | 6 | throw ConnectionFailed::fromUriAndReason($this->uri, $errorMessage); |
|
57 | } |
||
58 | |||
59 | 252 | $this->stream = $stream; |
|
60 | 252 | \stream_set_timeout($this->stream, $this->options['socket_timeout']); |
|
61 | |||
62 | 252 | $greeting = $this->read(IProto::GREETING_SIZE, 'Unable to read greeting.'); |
|
63 | |||
64 | 248 | return IProto::parseGreeting($greeting); |
|
65 | } |
||
66 | |||
67 | 258 | public function close() : void |
|
68 | { |
||
69 | 258 | if ($this->stream) { |
|
70 | 4 | \fclose($this->stream); |
|
71 | 4 | $this->stream = null; |
|
72 | } |
||
73 | 258 | } |
|
74 | |||
75 | 254 | public function isClosed() : bool |
|
79 | |||
80 | 214 | public function send(string $data) : string |
|
81 | { |
||
91 | |||
92 | 252 | private function read(int $length, string $errorMessage) : string |
|
101 | } |
||
102 |
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.