Completed
Pull Request — master (#41)
by Joel
07:57
created

RequestWriter::writeRequest()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 5
cts 6
cp 0.8333
rs 9.9332
c 0
b 0
f 0
cc 3
nc 3
nop 3
crap 3.0416
1
<?php
2
3
namespace Http\Client\Socket;
4
5
use Http\Client\Socket\Exception\BrokenPipeException;
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 int      $bufferSize
22
     *
23
     * @throws BrokenPipeException
24
     */
25 59
    protected function writeRequest($socket, RequestInterface $request, $bufferSize = 8192)
26
    {
27 59
        if (false === $this->fwrite($socket, $this->transformRequestHeadersToString($request))) {
28
            throw new BrokenPipeException('Failed to send request, underlying socket not accessible, (BROKEN EPIPE)', $request);
29
        }
30
31 59
        if ($request->getBody()->isReadable()) {
32 59
            $this->writeBody($socket, $request, $bufferSize);
33
        }
34 59
    }
35
36
    /**
37
     * Write Body of the request.
38
     *
39
     * @param resource $socket
40
     * @param int      $bufferSize
41
     *
42
     * @throws BrokenPipeException
43
     */
44 59
    protected function writeBody($socket, RequestInterface $request, $bufferSize = 8192)
45
    {
46 59
        $body = $request->getBody();
47
48 59
        if ($body->isSeekable()) {
49 59
            $body->rewind();
50
        }
51
52 59
        while (!$body->eof()) {
53 59
            $buffer = $body->read($bufferSize);
54
55 59
            if (false === $this->fwrite($socket, $buffer)) {
56
                throw new BrokenPipeException('An error occur when writing request to client (BROKEN EPIPE)', $request);
57
            }
58
        }
59 59
    }
60
61
    /**
62
     * Produce the header of request as a string based on a PSR Request.
63
     *
64
     *
65
     * @return string
66
     */
67 59
    protected function transformRequestHeadersToString(RequestInterface $request)
68
    {
69 59
        $message = vsprintf('%s %s HTTP/%s', [
70 59
            strtoupper($request->getMethod()),
71 59
            $request->getRequestTarget(),
72 59
            $request->getProtocolVersion(),
73 59
        ])."\r\n";
74
75 59
        foreach ($request->getHeaders() as $name => $values) {
76 59
            $message .= $name.': '.implode(', ', $values)."\r\n";
77
        }
78
79 59
        $message .= "\r\n";
80
81 59
        return $message;
82
    }
83
84
    /**
85
     * Replace fwrite behavior as api is broken in PHP.
86
     *
87
     * @see https://secure.phabricator.com/rPHU69490c53c9c2ef2002bc2dd4cecfe9a4b080b497
88
     *
89
     * @param resource $stream The stream resource
90
     * @param string   $bytes  Bytes written in the stream
91
     *
92
     * @return bool|int false if pipe is broken, number of bytes written otherwise
93
     */
94 59
    private function fwrite($stream, $bytes)
95
    {
96 59
        if (!strlen($bytes)) {
97 59
            return 0;
98
        }
99 59
        $result = @fwrite($stream, $bytes);
100 59
        if (0 !== $result) {
101
            // In cases where some bytes are witten (`$result > 0`) or
102
            // an error occurs (`$result === false`), the behavior of fwrite() is
103
            // correct. We can return the value as-is.
104 59
            return $result;
105
        }
106
        // If we make it here, we performed a 0-length write. Try to distinguish
107
        // between EAGAIN and EPIPE. To do this, we're going to `stream_select()`
108
        // the stream, write to it again if PHP claims that it's writable, and
109
        // consider the pipe broken if the write fails.
110
        $read = [];
111
        $write = [$stream];
112
        $except = [];
113
        @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...
114
        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...
115
            // The stream isn't writable, so we conclude that it probably really is
116
            // blocked and the underlying error was EAGAIN. Return 0 to indicate that
117
            // no data could be written yet.
118
            return 0;
119
        }
120
        // If we make it here, PHP **just** claimed that this stream is writable, so
121
        // perform a write. If the write also fails, conclude that these failures are
122
        // EPIPE or some other permanent failure.
123
        $result = @fwrite($stream, $bytes);
124
        if (0 !== $result) {
125
            // The write worked or failed explicitly. This value is fine to return.
126
            return $result;
127
        }
128
        // We performed a 0-length write, were told that the stream was writable, and
129
        // then immediately performed another 0-length write. Conclude that the pipe
130
        // is broken and return `false`.
131
        return false;
132
    }
133
}
134