SimpleHttpRequester::makeHttpRequest()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 31
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
eloc 17
c 0
b 0
f 0
dl 0
loc 31
ccs 0
cts 23
cp 0
rs 9.3888
cc 5
nc 5
nop 1
crap 30
1
<?php
2
3
namespace HtaccessCapabilityTester;
4
5
class SimpleHttpRequester implements HttpRequesterInterface
6
{
7
    /**
8
     * Make a HTTP request to a URL.
9
     *
10
     * @param  string  $url  The URL to make the HTTP request to
11
     *
12
     * @return  HttpResponse  A HttpResponse object, which simply contains body, status code and response headers.
13
     *                        In case the request itself fails, the status code is "0" and the body should contain
14
     *                        error description (if available)
15
     */
16
    public function makeHttpRequest($url)
17
    {
18
        // PS: We suppress the E_WARNING level error generated on failure
19
        $body = @file_get_contents($url);
20
        if ($body === false) {
21
            //$body = '';
22
            return new HttpResponse('The following request failed: file_get_contents(' . $url . ')', '0', []);
23
        }
24
25
        // $http_response_header materializes out of thin air when file_get_contents() is called
26
27
        // Get status code
28
        $statusLine = $http_response_header[0];
29
        preg_match('{HTTP\/\S*\s(\d{3})}', $statusLine, $match);
30
        $statusCode = $match[1];
31
32
        // Create headers map
33
        $headersMap = [];
34
        foreach ($http_response_header as $header) {
35
            $pos = strpos($header, ':');
36
            if ($pos > 0) {
37
                $fieldName = strtolower(trim(substr($header, 0, $pos)));
38
                $value = trim(substr($header, $pos + 1));
39
                if (!isset($headersMap[$fieldName])) {
40
                    $headersMap[$fieldName] = $value;
41
                } else {
42
                    $headersMap[$fieldName] .= ', ' . $value;
43
                }
44
            }
45
        }
46
        return new HttpResponse($body, $statusCode, $headersMap);
47
    }
48
}
49