Completed
Pull Request — master (#288)
by Bai
13:51
created

Client::userAgent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 14
ccs 8
cts 8
cp 1
crap 1
rs 9.7998
c 0
b 0
f 0
1
<?php
2
namespace Qiniu\Http;
3
4
use Qiniu\Config;
5
use Qiniu\Http\Request;
6
use Qiniu\Http\Response;
7
8
final class Client
9
{
10 57
    public static function get($url, array $headers = array())
11
    {
12 57
        $request = new Request('GET', $url, $headers);
13 57
        return self::sendRequest($request);
14
    }
15
16
    public static function delete($url, array $headers = array())
17
    {
18
        $request = new Request('DELETE', $url, $headers);
19
        return self::sendRequest($request);
20
    }
21
22 45
    public static function post($url, $body, array $headers = array())
23
    {
24 45
        $request = new Request('POST', $url, $headers, $body);
25 45
        return self::sendRequest($request);
26
    }
27
28
    public static function multipartPost(
29
        $url,
30
        $fields,
31
        $name,
32
        $fileName,
33
        $fileBody,
34
        $mimeType = null,
35
        array $headers = array()
36
    ) {
37
        $data = array();
38
        $mimeBoundary = md5(microtime());
39
40
        foreach ($fields as $key => $val) {
41
            array_push($data, '--' . $mimeBoundary);
42
            array_push($data, "Content-Disposition: form-data; name=\"$key\"");
43
            array_push($data, '');
44
            array_push($data, $val);
45
        }
46
47
        array_push($data, '--' . $mimeBoundary);
48
        $finalMimeType = empty($mimeType) ? 'application/octet-stream' : $mimeType;
49
        $finalFileName = self::escapeQuotes($fileName);
50
        array_push($data, "Content-Disposition: form-data; name=\"$name\"; filename=\"$finalFileName\"");
51
        array_push($data, "Content-Type: $finalMimeType");
52
        array_push($data, '');
53
        array_push($data, $fileBody);
54
55
        array_push($data, '--' . $mimeBoundary . '--');
56
        array_push($data, '');
57
58
        $body = implode("\r\n", $data);
59
        $contentType = 'multipart/form-data; boundary=' . $mimeBoundary;
60
        $headers['Content-Type'] = $contentType;
61
        $request = new Request('POST', $url, $headers, $body);
62
        return self::sendRequest($request);
63
    }
64
65 102
    private static function userAgent()
66
    {
67 102
        $sdkInfo = "QiniuPHP/" . Config::SDK_VER;
68
69 102
        $systemInfo = php_uname("s");
70 102
        $machineInfo = php_uname("m");
71
72 102
        $envInfo = "($systemInfo/$machineInfo)";
73
74 102
        $phpVer = phpversion();
75
76 102
        $ua = "$sdkInfo $envInfo PHP/$phpVer";
77 102
        return $ua;
78
    }
79
80 102
    public static function sendRequest($request)
81
    {
82 102
        $t1 = microtime(true);
83 102
        $ch = curl_init();
84
        $options = array(
85 102
            CURLOPT_USERAGENT => self::userAgent(),
86 102
            CURLOPT_RETURNTRANSFER => true,
87 102
            CURLOPT_SSL_VERIFYPEER => false,
88 102
            CURLOPT_SSL_VERIFYHOST => false,
89 102
            CURLOPT_HEADER => true,
90 102
            CURLOPT_NOBODY => false,
91 102
            CURLOPT_CUSTOMREQUEST => $request->method,
92 102
            CURLOPT_URL => $request->url,
93 102
        );
94
95
        // Handle open_basedir & safe mode
96 102
        if (!ini_get('safe_mode') && !ini_get('open_basedir')) {
97 102
            $options[CURLOPT_FOLLOWLOCATION] = true;
98 102
        }
99
100 102
        if (!empty($request->headers)) {
101 48
            $headers = array();
102 48
            foreach ($request->headers as $key => $val) {
103 48
                array_push($headers, "$key: $val");
104 48
            }
105 48
            $options[CURLOPT_HTTPHEADER] = $headers;
106 48
        }
107 102
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
108
109 102
        if (!empty($request->body)) {
110 24
            $options[CURLOPT_POSTFIELDS] = $request->body;
111 24
        }
112 102
        curl_setopt_array($ch, $options);
113 102
        $result = curl_exec($ch);
114 102
        $t2 = microtime(true);
115 102
        $duration = round($t2 - $t1, 3);
116 102
        $ret = curl_errno($ch);
117 102
        if ($ret !== 0) {
118 6
            $r = new Response(-1, $duration, array(), null, curl_error($ch));
119 6
            curl_close($ch);
120 6
            return $r;
121
        }
122 99
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
123 99
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
124 99
        $headers = self::parseHeaders(substr($result, 0, $header_size));
125 99
        $body = substr($result, $header_size);
126 99
        curl_close($ch);
127 99
        return new Response($code, $duration, $headers, $body, null);
128
    }
129
130 99
    private static function parseHeaders($raw)
131
    {
132 99
        $headers = array();
133 99
        $headerLines = explode("\r\n", $raw);
134 99
        foreach ($headerLines as $line) {
135 99
            $headerLine = trim($line);
136 99
            $kv = explode(':', $headerLine);
137 99
            if (count($kv) > 1) {
138 99
                $kv[0] =self::ucwordsHyphen($kv[0]);
139 99
                $headers[$kv[0]] = trim($kv[1]);
140 99
            }
141 99
        }
142 99
        return $headers;
143
    }
144
145
    private static function escapeQuotes($str)
146
    {
147
        $find = array("\\", "\"");
148
        $replace = array("\\\\", "\\\"");
149
        return str_replace($find, $replace, $str);
150
    }
151
    
152 99
    private static function ucwordsHyphen($str)
153
    {
154 99
        return str_replace('- ', '-', ucwords(str_replace('-', '- ', $str)));
155
    }
156
}
157