Passed
Push — master ( 01f538...95b550 )
by Igor
04:19 queued 59s
created

SocketConnection::sendRequest()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
ccs 3
cts 4
cp 0.75
crap 2.0625
rs 10
c 1
b 0
f 0
1
<?php
2
/*
3
 * This file is part of json-rpc-client.
4
 *
5
 * (c) Igor Lazarev <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Strider2038\JsonRpcClient\Transport\Socket;
12
13
use Strider2038\JsonRpcClient\Exception\ConnectionLostException;
14
use Strider2038\JsonRpcClient\Exception\RemoteProcedureCallFailedException;
15
16
/**
17
 * @author Igor Lazarev <[email protected]>
18
 */
19
class SocketConnection
20
{
21
    /** @var resource */
22
    private $stream;
23
24
    /** @var string */
25
    private $url;
26
27
    /** @var int */
28
    private $requestTimeoutUs;
29
30 5
    public function __construct($stream, string $url, int $requestTimeoutUs)
31
    {
32 5
        $this->stream = $stream;
33 5
        $this->url = $url;
34 5
        $this->requestTimeoutUs = $requestTimeoutUs;
35 5
    }
36
37 5
    public function __destruct()
38
    {
39 5
        if (is_resource($this->stream)) {
40 5
            fclose($this->stream);
41
        }
42 5
    }
43
44
    /**
45
     * @throws ConnectionLostException
46
     */
47 5
    public function sendRequest(string $request): void
48
    {
49 5
        if (false === fwrite($this->stream, $request."\n")) {
50
            throw new ConnectionLostException($this->url, 'failed to write data into stream');
51
        }
52
53 5
        fflush($this->stream);
54 5
    }
55
56
    /**
57
     * @throws RemoteProcedureCallFailedException
58
     */
59 5
    public function receiveResponse(): string
60
    {
61 5
        $response = fgets($this->stream);
62
63 5
        if (false === $response) {
64 1
            $this->checkForTimeout($this->stream);
65
66
            throw new RemoteProcedureCallFailedException(sprintf('Failed to get response from %s.', $this->url));
67
        }
68
69 4
        return $response;
70
    }
71
72 5
    public function isClosed(): bool
73
    {
74 5
        return feof($this->stream);
75
    }
76
77
    /**
78
     * @param resource $stream
79
     *
80
     * @throws RemoteProcedureCallFailedException
81
     */
82 1
    private function checkForTimeout($stream): void
83
    {
84 1
        $info = stream_get_meta_data($stream);
85
86 1
        if ($info['timed_out']) {
87 1
            $error = sprintf('Request to %s failed by timeout %d us.', $this->url, $this->requestTimeoutUs);
88
89 1
            throw new RemoteProcedureCallFailedException($error);
90
        }
91
    }
92
}
93