Completed
Push — master ( 88a5ed...6cb890 )
by Joel
03:51
created

RequestWriter   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 123
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 73.33%
Metric Value
wmc 14
lcom 1
cbo 3
dl 0
loc 123
ccs 33
cts 45
cp 0.7333
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A writeRequest() 0 10 3
A writeBody() 0 16 4
A transformRequestHeadersToString() 0 16 2
B fwrite() 0 39 5
1
<?php
2
3
namespace Http\Client\Socket;
4
5
use Http\Client\Exception\NetworkException;
6
use Psr\Http\Message\RequestInterface;
7
8
/**
9
 * Method for writing request
10
 *
11
 * Mainly used by SocketHttpClient
12
 *
13
 * @author Joel Wurtz <[email protected]>
14
 */
15
trait RequestWriter
16
{
17
    /**
18
     * Write a request to a socket
19
     *
20
     * @param resource         $socket
21
     * @param RequestInterface $request
22
     * @param integer          $bufferSize
23
     *
24
     * @throws \Http\Client\Exception\NetworkException
25
     */
26 59
    protected function writeRequest($socket, RequestInterface $request, $bufferSize = 8192)
27
    {
28 59
        if (false === $this->fwrite($socket, $this->transformRequestHeadersToString($request))) {
29
            throw new NetworkException("Failed to send request, underlying socket not accessible, (BROKEN EPIPE)", $request);
30
        }
31
32 59
        if ($request->getBody()->isReadable()) {
33 59
            $this->writeBody($socket, $request, $bufferSize);
34 59
        }
35 59
    }
36
37
    /**
38
     * Write Body of the request
39
     *
40
     * @param resource         $socket
41
     * @param RequestInterface $request
42
     * @param integer          $bufferSize
43
     *
44
     * @throws \Http\Client\Exception\NetworkException
45
     * @throws \Http\Client\Exception\RequestException
46
     */
47 59
    protected function writeBody($socket, RequestInterface $request, $bufferSize = 8192)
48
    {
49 59
        $body = $request->getBody();
50
51 59
        if ($body->isSeekable()) {
52 59
            $body->rewind();
53 59
        }
54
55 59
        while (!$body->eof()) {
56 59
            $buffer = $body->read($bufferSize);
57
58 59
            if (false === $this->fwrite($socket, $buffer)) {
59
                throw new NetworkException("An error occur when writing request to client (BROKEN EPIPE)", $request);
60
            }
61 59
        }
62 59
    }
63
64
    /**
65
     * Produce the header of request as a string based on a PSR Request
66
     *
67
     * @param RequestInterface $request
68
     *
69
     * @return string
70
     */
71 59
    protected function transformRequestHeadersToString(RequestInterface $request)
72
    {
73 59
        $message  = vsprintf('%s %s HTTP/%s', [
74 59
            strtoupper($request->getMethod()),
75 59
            $request->getRequestTarget(),
76 59
            $request->getProtocolVersion()
77 59
        ])."\r\n";
78
79 59
        foreach ($request->getHeaders() as $name => $values) {
80 59
            $message .= $name.': '.implode(', ', $values)."\r\n";
81 59
        }
82
83 59
        $message .= "\r\n";
84
85 59
        return $message;
86
    }
87
88
    /**
89
     * Replace fwrite behavior as api is broken in PHP
90
     *
91
     * @see https://secure.phabricator.com/rPHU69490c53c9c2ef2002bc2dd4cecfe9a4b080b497
92
     *
93
     * @param resource $stream The stream resource
94
     * @param string   $bytes  Bytes written in the stream
95
     *
96
     * @return bool|int false if pipe is broken, number of bytes written otherwise
97
     */
98 59
    private function fwrite($stream, $bytes)
99
    {
100 59
        if (!strlen($bytes)) {
101 39
            return 0;
102
        }
103 59
        $result = @fwrite($stream, $bytes);
104 59
        if ($result !== 0) {
105
            // In cases where some bytes are witten (`$result > 0`) or
106
            // an error occurs (`$result === false`), the behavior of fwrite() is
107
            // correct. We can return the value as-is.
108 59
            return $result;
109
        }
110
        // If we make it here, we performed a 0-length write. Try to distinguish
111
        // between EAGAIN and EPIPE. To do this, we're going to `stream_select()`
112
        // the stream, write to it again if PHP claims that it's writable, and
113
        // consider the pipe broken if the write fails.
114
        $read = [];
115
        $write = [$stream];
116
        $except = [];
117
        @stream_select($read, $write, $except, 0);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
118
        if (!$write) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $write of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

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.

Loading history...
119
            // The stream isn't writable, so we conclude that it probably really is
120
            // blocked and the underlying error was EAGAIN. Return 0 to indicate that
121
            // no data could be written yet.
122
            return 0;
123
        }
124
        // If we make it here, PHP **just** claimed that this stream is writable, so
125
        // perform a write. If the write also fails, conclude that these failures are
126
        // EPIPE or some other permanent failure.
127
        $result = @fwrite($stream, $bytes);
128
        if ($result !== 0) {
129
            // The write worked or failed explicitly. This value is fine to return.
130
            return $result;
131
        }
132
        // We performed a 0-length write, were told that the stream was writable, and
133
        // then immediately performed another 0-length write. Conclude that the pipe
134
        // is broken and return `false`.
135
        return false;
136
    }
137
}
138