-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequest.php
More file actions
98 lines (78 loc) · 3.1 KB
/
Request.php
File metadata and controls
98 lines (78 loc) · 3.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
namespace ExportComments;
use ExportComments\ExportCommentsException;
class Request {
public $token;
public $endpoint;
function parseHeaders($headers) {
$head = array();
foreach ($headers as $k => $v) {
$t = explode(':', $v, 2);
if (isset($t[1]))
$head[trim($t[0])] = trim($t[1]);
else {
$head[] = $v;
if (preg_match("#HTTP/[0-9\.]+\s+([0-9]+)#", $v, $out))
$head['response_code'] = intval($out[1]);
}
}
return $head;
}
function make_request($url, $method, $data = null, $retry_if_throttled = true) {
$headers = "Content-type: application/json\r\n" .
"X-AUTH-TOKEN: $this->token\r\n" .
"User-Agent: php-sdk\r\n";
$options = array(
'http' => array(
'header' => $headers,
'method' => $method,
'ignore_errors' => true,
),
);
if ($data !== null && ($method === 'POST' || $method === 'PUT')) {
$options['http']['content'] = json_encode($data);
}
$context = stream_context_create($options);
$retries_left = 3;
while ($retries_left > 0) {
$result = @file_get_contents($url, false, $context);
$headers = $this->parseHeaders($http_response_header);
$response_json = json_decode($result, true);
if ($headers['response_code'] == 429 && $retry_if_throttled && $retries_left > 1) {
$wait = isset($response_json['seconds_to_wait']) ? intval($response_json['seconds_to_wait']) : 2;
sleep($wait);
$retries_left--;
continue;
}
if ($headers['response_code'] != 200 && $headers['response_code'] != 201) {
$error_message = isset($response_json['error']) ? $response_json['error'] : 'Unknown error';
throw new ExportCommentsException($error_message);
}
return array($response_json, $headers);
}
throw new ExportCommentsException('Max retries exceeded');
}
/**
* Make a raw request that returns the response body as a string (for file downloads).
*/
function make_raw_request($url, $method = 'GET') {
$headers = "X-AUTH-TOKEN: $this->token\r\n" .
"User-Agent: php-sdk\r\n";
$options = array(
'http' => array(
'header' => $headers,
'method' => $method,
'ignore_errors' => true,
),
);
$context = stream_context_create($options);
$result = @file_get_contents($url, false, $context);
$headers = $this->parseHeaders($http_response_header);
if ($headers['response_code'] != 200) {
$response_json = json_decode($result, true);
$error_message = isset($response_json['error']) ? $response_json['error'] : 'Download failed';
throw new ExportCommentsException($error_message);
}
return $result;
}
}