Completed
Pull Request — master (#229)
by r
14:58 queued 12:48
created

Client::multipartPost()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 36
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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