Test Failed
Push — master ( 29d761...e93c95 )
by Alexpts
01:54
created

Socket::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
declare(strict_types=1);
3
4
namespace PTS\Transport;
5
6
abstract class Socket implements TransportInterface
7
{
8
9
    /**
10
     * @var resource|null|false
11
     */
12
    protected $socket;
13
14
    /** @var string - udp:// tcp:// */
15
    protected $socketPrefix = '';
16
17
    protected $errorNumber = 0;
18
    protected $errorMessage = '';
19
20
    /** @var Writer */
21
    protected $writer;
22
23
    public function __construct(Writer $writer = null)
24
    {
25
        $this->writer = $writer ?? new Writer;
26
    }
27
28
    /**
29
     * @param string $address
30
     * @param int $port
31
     * @param array $options
32
     *
33
     * @return TransportInterface
34
     */
35
    public function connect(string $address, int $port = 0, array $options = []): TransportInterface
36
    {
37
        $timeout = (float)($options['timeout'] ??(float) ini_get('default_socket_timeout'));
38
        $url = $this->socketPrefix . $address;
39
        $this->socket = @fsockopen($url, $port, $this->errorNumber, $this->errorMessage, $timeout);
40
41
        return $this;
42
    }
43
44
    /**
45
     * @param string $buffer
46
     * @param int|null $length - записать число байт в сокет
47
     *
48
     * @return false|int число записанных байт или false
49
     */
50
    public function write(string $buffer, int $length = null): int
51
    {
52
        return $this->writer->write($this->socket, $buffer, $length);
0 ignored issues
show
Bug introduced by
It seems like $this->socket can also be of type false or null; however, PTS\Transport\Writer::write() does only seem to accept resource, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
53
    }
54
55
    public function isConnected(): bool
56
    {
57
        return is_resource($this->socket) && !feof($this->socket);
58
    }
59
60
    public function close(): void
61
    {
62
        $this->socket && fclose($this->socket);
63
        $this->socket = null;
64
    }
65
}
66