SocketConnection::__destruct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 2
nc 2
nop 0
crap 2
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
 * @internal
18
 *
19
 * @author Igor Lazarev <[email protected]>
20
 */
21
class SocketConnection
22
{
23
    /** @var resource */
24
    private $stream;
25
26
    private string $url;
27
28
    private int $requestTimeoutUs;
29
30
    public function __construct($stream, string $url, int $requestTimeoutUs)
31
    {
32 5
        $this->stream = $stream;
33
        $this->url = $url;
34 5
        $this->requestTimeoutUs = $requestTimeoutUs;
35 5
    }
36 5
37 5
    public function __destruct()
38
    {
39 5
        if (is_resource($this->stream)) {
40
            fclose($this->stream);
41 5
        }
42 5
    }
43
44 5
    /**
45
     * @throws ConnectionLostException
46
     */
47
    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 5
        }
52
53
        fflush($this->stream);
54
    }
55 5
56 5
    /**
57
     * @throws RemoteProcedureCallFailedException
58
     */
59
    public function receiveResponse(): string
60
    {
61 5
        $response = fgets($this->stream);
62
63 5
        if (false === $response) {
64
            $this->checkForTimeout($this->stream);
65 5
66 1
            throw new RemoteProcedureCallFailedException(sprintf('Failed to get response from %s.', $this->url));
67
        }
68
69
        return $response;
70
    }
71 4
72
    public function isClosed(): bool
73
    {
74 5
        return feof($this->stream);
75
    }
76 5
77
    /**
78
     * @param resource $stream
79
     *
80
     * @throws RemoteProcedureCallFailedException
81
     */
82
    private function checkForTimeout($stream): void
83
    {
84 1
        $info = stream_get_meta_data($stream);
85
86 1
        if ($info['timed_out']) {
87
            $error = sprintf('Request to %s failed by timeout %d us.', $this->url, $this->requestTimeoutUs);
88 1
89 1
            throw new RemoteProcedureCallFailedException($error);
90
        }
91 1
    }
92
}
93