ZurlResponse   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 89
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 0
dl 0
loc 89
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getResponse() 0 28 4
A failed() 0 13 3
A curlHasResult() 0 4 1
A isJson() 0 6 1
A isHTML() 0 4 2
1
<?php
2
3
namespace Zengine\Zurl;
4
5
6
class ZurlResponse
7
{
8
    protected $ch;
9
10
    protected $curlResult;
11
12
    public function __construct($ch)
13
    {
14
        $this->ch = $ch;
15
        $this->curlResult = curl_exec($this->ch);
16
    }
17
18
    public function getResponse()
19
    {
20
        $header_len = curl_getinfo($this->ch, CURLINFO_HEADER_SIZE);
21
        $header = substr($this->curlResult, 0, $header_len);
22
        $headerLines = explode("\r\n", $header);
23
        $body = substr($this->curlResult, $header_len);
24
        $headers = [];
25
        foreach ($headerLines as $i => $line) {
26
            $headerLine = explode(':', $line);
27
            if ($i === 0) {
28
                $temp = explode(' ', $headerLine[0]);
29
                $headers['Http_protocol'] = $temp[0];
30
                $headers['Http_code'] = $temp[1];
31
                $headers['Http_message'] = $temp[2];
32
            }
33
            if (count($headerLine) >= 2) {
34
                $headers[$headerLine[0]] = $headerLine[1];
35
            }
36
        }
37
38
        return [
39
            'http_code'       => curl_getinfo($this->ch, CURLINFO_HTTP_CODE),
40
            'connection_time' => curl_getinfo($this->ch, CURLINFO_CONNECT_TIME),
41
            'total_time'      => curl_getinfo($this->ch, CURLINFO_TOTAL_TIME),
42
            'headers'         => $headers,
43
            'body'            => $body,
44
        ];
45
    }
46
47
    /**
48
     * @return bool
49
     */
50
    public function failed()
51
    {
52
        if (curl_getinfo($this->ch, CURLINFO_HTTP_CODE) === 0) {
53
54
            return true;
55
        }
56
57
        if (!$this->curlHasResult()) {
58
            return false;
59
        }
60
61
        return curl_getinfo($this->ch, CURLINFO_HTTP_CODE) >= 400;
62
    }
63
64
    /**
65
     * @return bool
66
     */
67
    protected function curlHasResult()
68
    {
69
        return (bool)$this->curlResult;
70
    }
71
72
    /**
73
     * @param $string
74
     *
75
     * @return bool
76
     */
77
    protected function isJson($string)
78
    {
79
        json_decode($string);
80
81
        return (json_last_error() == JSON_ERROR_NONE);
82
    }
83
84
    /**
85
     * @param $string
86
     *
87
     * @return bool
88
     */
89
    protected function isHTML($string)
90
    {
91
        return $string != strip_tags($string) ? true : false;
92
    }
93
94
}
95