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

ResponseReader::createStream()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 4
cts 5
cp 0.8
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 2.032
1
<?php
2
3
namespace Http\Client\Socket;
4
5
use Http\Client\Socket\Exception\BrokenPipeException;
6
use Http\Client\Socket\Exception\TimeoutException;
7
use Http\Message\ResponseFactory;
8
use Psr\Http\Message\RequestInterface;
9
use Psr\Http\Message\ResponseInterface;
10
11
/**
12
 * Method for reading response.
13
 *
14
 * Mainly used by SocketHttpClient
15
 *
16
 * @author Joel Wurtz <[email protected]>
17
 */
18
trait ResponseReader
19
{
20
    /**
21
     * @var ResponseFactory For creating response
22
     */
23
    protected $responseFactory;
24
25
    /**
26
     * Read a response from a socket.
27
     *
28
     * @param resource $socket
29
     *
30
     * @throws TimeoutException    When the socket timed out
31
     * @throws BrokenPipeException When the response cannot be read
32
     *
33
     * @return ResponseInterface
34
     */
35 59
    protected function readResponse(RequestInterface $request, $socket)
36
    {
37 59
        $headers = [];
38 59
        $reason = null;
39
40 59
        while (false !== ($line = fgets($socket))) {
41 58
            if ('' === rtrim($line)) {
42 58
                break;
43
            }
44 58
            $headers[] = trim($line);
45
        }
46
47 59
        $metadatas = stream_get_meta_data($socket);
48
49 59
        if (array_key_exists('timed_out', $metadatas) && true === $metadatas['timed_out']) {
50
            throw new TimeoutException('Error while reading response, stream timed out', null, null, $request);
51
        }
52
53 59
        $parts = explode(' ', array_shift($headers), 3);
54
55 59
        if (count($parts) <= 1) {
56 1
            throw new BrokenPipeException('Cannot read the response', $request);
57
        }
58
59 58
        $protocol = substr($parts[0], -3);
60 58
        $status = $parts[1];
61
62 58
        if (isset($parts[2])) {
63 58
            $reason = $parts[2];
64
        }
65
66
        // Set the size on the stream if it was returned in the response
67 58
        $responseHeaders = [];
68
69 58
        foreach ($headers as $header) {
70 58
            $headerParts = explode(':', $header, 2);
71
72 58
            if (!array_key_exists(trim($headerParts[0]), $responseHeaders)) {
73 58
                $responseHeaders[trim($headerParts[0])] = [];
74
            }
75
76 58
            $responseHeaders[trim($headerParts[0])][] = isset($headerParts[1])
77 58
                ? trim($headerParts[1])
78 58
                : '';
79
        }
80
81 58
        $response = $this->responseFactory->createResponse($status, $reason, $responseHeaders, null, $protocol);
82 58
        $stream = $this->createStream($socket, $response);
83
84 58
        return $response->withBody($stream);
85
    }
86
87
    /**
88
     * Create the stream.
89
     *
90
     * @param $socket
91
     *
92
     * @return Stream
93
     */
94 58
    protected function createStream($socket, ResponseInterface $response)
95
    {
96 58
        $size = null;
97
98 58
        if ($response->hasHeader('Content-Length')) {
99
            $size = (int) $response->getHeaderLine('Content-Length');
100
        }
101
102 58
        return new Stream($socket, $size);
103
    }
104
}
105