Completed
Push — master ( 5855e7...4c70a1 )
by Robin
02:57
created

Socket::setBlocking()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 0
cts 4
cp 0
rs 9.4285
cc 3
eloc 4
nc 2
nop 1
crap 12
1
<?php
2
3
namespace Rvdv\Nntp\Socket;
4
5
use Rvdv\Nntp\Exception\SocketException;
6
7
/**
8
 * @author Robin van der Vleuten <[email protected]>
9
 */
10
class Socket implements SocketInterface
11
{
12
    /**
13
     * @var resource
14
     */
15
    private $resource;
16
17
    /**
18
     * {@inheritdoc}
19
     */
20
    public function setBlocking($blocking)
21
    {
22
        if (!stream_set_blocking($this->resource, $blocking ? 1 : 0)) {
23
            throw new SocketException();
24
        }
25
26
        return $this;
27
    }
28
29
    /**
30
     * {@inheritdoc}
31
     */
32
    public function enableCrypto($enable, $cryptoType = STREAM_CRYPTO_METHOD_TLS_CLIENT)
33
    {
34
        if (!stream_socket_enable_crypto($this->resource, $enable, $cryptoType)) {
35
            throw new SocketException();
36
        }
37
38
        return $this;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function connect($address, $timeout = null)
45
    {
46
        if (!$this->resource = stream_socket_client($address, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT)) {
47
            throw new SocketException(sprintf('Connection to %s failed: %s', $address, $errstr));
48
        }
49
50
        return $this;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function disconnect()
57
    {
58
        if (!fclose($this->resource)) {
59
            throw new SocketException();
60
        }
61
62
        return $this;
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    public function eof()
69
    {
70
        return feof($this->resource);
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     */
76
    public function read($length)
77
    {
78
        if (($data = fread($this->resource, $length)) === false) {
79
            throw new SocketException();
80
        }
81
82
        return $data;
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88
    public function write($data)
89
    {
90
        if (($bytes = fwrite($this->resource, $data)) === false) {
91
            throw new SocketException();
92
        }
93
94
        return $bytes;
95
    }
96
}
97