Completed
Push — master ( 29bda6...e00326 )
by David
9s
created

StreamClient::retrieveResponse()   C

Complexity

Conditions 11
Paths 25

Size

Total Lines 51
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 51
rs 5.7333
c 1
b 0
f 0
cc 11
eloc 31
nc 25
nop 4

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace OAuth\Common\Http\Client;
4
5
use OAuth\Common\Http\Exception\TokenResponseException;
6
use OAuth\Common\Http\Uri\UriInterface;
7
8
/**
9
 * Client implementation for streams/file_get_contents
10
 */
11
class StreamClient extends AbstractClient
12
{
13
    /**
14
     * Any implementing HTTP providers should send a request to the provided endpoint with the parameters.
15
     * They should return, in string form, the response body and throw an exception on error.
16
     *
17
     * @param UriInterface $endpoint
18
     * @param mixed        $requestBody
19
     * @param array        $extraHeaders
20
     * @param string       $method
21
     *
22
     * @return string
23
     *
24
     * @throws TokenResponseException
25
     * @throws \InvalidArgumentException
26
     */
27
    public function retrieveResponse(
28
        UriInterface $endpoint,
29
        $requestBody,
30
        array $extraHeaders = array(),
31
        $method = 'POST'
32
    ) {
33
        // Normalize method name
34
        $method = strtoupper($method);
35
36
        $this->normalizeHeaders($extraHeaders);
37
38
        if ($method === 'GET' && !empty($requestBody)) {
39
            throw new \InvalidArgumentException('No body expected for "GET" request.');
40
        }
41
42
        if (!isset($extraHeaders['Content-Type']) && $method === 'POST' && is_array($requestBody)) {
43
            $extraHeaders['Content-Type'] = 'Content-Type: application/x-www-form-urlencoded';
44
        }
45
46
        $host = 'Host: '.$endpoint->getHost();
47
        // Append port to Host if it has been specified
48
        if ($endpoint->hasExplicitPortSpecified()) {
49
            $host .= ':'.$endpoint->getPort();
50
        }
51
52
        $extraHeaders['Host']       = $host;
53
        $extraHeaders['Connection'] = 'Connection: close';
54
55
        if (is_array($requestBody)) {
56
            $requestBody = http_build_query($requestBody, '', '&');
57
        }
58
        $extraHeaders['Content-length'] = 'Content-length: '.strlen($requestBody);
59
60
        $context = $this->generateStreamContext($requestBody, $extraHeaders, $method);
61
62
        $level = error_reporting(0);
63
        $response = file_get_contents($endpoint->getAbsoluteUri(), false, $context);
64
        error_reporting($level);
65
        if (false === $response) {
66
            $lastError = error_get_last();
67
            if (is_null($lastError)) {
68
                throw new TokenResponseException(
69
                    'Failed to request resource. HTTP Code: ' .
70
                    ((isset($http_response_header[0]))?$http_response_header[0]:'No response')
71
                );
72
            }
73
            throw new TokenResponseException($lastError['message']);
74
        }
75
76
        return $response;
77
    }
78
79
    private function generateStreamContext($body, $headers, $method)
80
    {
81
        return stream_context_create(
82
            array(
83
                'http' => array(
84
                    'method'           => $method,
85
                    'header'           => implode("\r\n", array_values($headers)),
86
                    'content'          => $body,
87
                    'protocol_version' => '1.1',
88
                    'user_agent'       => $this->userAgent,
89
                    'max_redirects'    => $this->maxRedirects,
90
                    'timeout'          => $this->timeout
91
                ),
92
            )
93
        );
94
    }
95
}
96