-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathClient.php
More file actions
200 lines (170 loc) · 6.68 KB
/
Client.php
File metadata and controls
200 lines (170 loc) · 6.68 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
<?php
namespace Tinify;
class Client {
const API_ENDPOINT = "https://api.tinify.com";
const RETRY_COUNT = 1;
const RETRY_DELAY = 500;
private $options;
/**
* @return string
*/
public static function userAgent() {
$curl = curl_version();
return "Tinify/" . VERSION . " PHP/" . PHP_VERSION . " curl/" . $curl["version"];
}
/**
* @return string
*/
private static function caBundle() {
return __DIR__ . "/../data/cacert.pem";
}
/**
* @param string $key
* @param string|null $app_identifier
* @param string|null $proxy
* @throws ClientException
* @throws ConnectionException
*/
function __construct($key, $app_identifier = NULL, $proxy = NULL) {
$curl = curl_version();
if (!($curl["features"] & CURL_VERSION_SSL)) {
throw new ClientException("Your curl version does not support secure connections");
}
if ($curl["version_number"] < 0x071201) {
$version = $curl["version"];
throw new ClientException("Your curl version {$version} is outdated; please upgrade to 7.18.1 or higher");
}
# Set minimum TLS version to 1.2, CURL_SSLVERSION_TLSv1_2 is not available in curl < 7.34.0
# Additionally old PHP versions may not support this constant
$tlsVersion = ($curl["version_number"] < 0x072200)
? 6
: (defined('CURL_SSLVERSION_TLSv1_2') ? CURL_SSLVERSION_TLSv1_2 : 6);
$this->options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_USERPWD => "api:" . $key,
CURLOPT_CAINFO => self::caBundle(),
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_USERAGENT => join(" ", array_filter(array(self::userAgent(), $app_identifier))),
CURLOPT_SSLVERSION => $tlsVersion,
);
if ($proxy) {
$parts = parse_url($proxy);
if (isset($parts["host"])) {
$this->options[CURLOPT_PROXYTYPE] = CURLPROXY_HTTP;
$this->options[CURLOPT_PROXY] = $parts["host"];
} else {
throw new ConnectionException("Invalid proxy");
}
if (isset($parts["port"])) {
$this->options[CURLOPT_PROXYPORT] = $parts["port"];
}
$creds = "";
if (isset($parts["user"])) $creds .= $parts["user"];
if (isset($parts["pass"])) $creds .= ":" . $parts["pass"];
if ($creds) {
$this->options[CURLOPT_PROXYAUTH] = CURLAUTH_ANY;
$this->options[CURLOPT_PROXYUSERPWD] = $creds;
}
}
}
/**
* @param string $method
* @param string $url
* @param string|array|null $body
* @return \stdClass Object with 'body' (string) and 'headers' (array) properties
* @throws AccountException
* @throws ClientException
* @throws ServerException
* @throws ConnectionException
*/
function request($method, $url, $body = NULL) {
$header = array();
if (is_array($body)) {
if (!empty($body)) {
$body = json_encode($body);
array_push($header, "Content-Type: application/json");
} else {
$body = NULL;
}
}
for ($retries = self::RETRY_COUNT; $retries >= 0; $retries--) {
if ($retries < self::RETRY_COUNT) {
usleep(self::RETRY_DELAY * 1000);
}
$request = curl_init();
if ($request === false || $request === null) {
throw new ConnectionException(
"Error while connecting: curl extension is not functional or disabled."
);
}
curl_setopt_array($request, $this->options);
$url = strtolower(substr($url, 0, 6)) == "https:" ? $url : self::API_ENDPOINT . $url;
curl_setopt($request, CURLOPT_URL, $url);
curl_setopt($request, CURLOPT_CUSTOMREQUEST, strtoupper($method));
if (count($header) > 0) {
curl_setopt($request, CURLOPT_HTTPHEADER, $header);
}
if ($body) {
curl_setopt($request, CURLOPT_POSTFIELDS, $body);
}
$response = curl_exec($request);
if (is_string($response)) {
$status = curl_getinfo($request, CURLINFO_HTTP_CODE);
$headerSize = curl_getinfo($request, CURLINFO_HEADER_SIZE);
if (PHP_VERSION_ID < 80000) {
curl_close($request);
} else {
unset($request);
}
$headers = self::parseHeaders(substr($response, 0, $headerSize));
$responseBody = substr($response, $headerSize);
if (isset($headers["compression-count"])) {
Tinify::setCompressionCount(intval($headers["compression-count"]));
}
if ($status >= 200 && $status <= 299) {
return (object) array("body" => $responseBody, "headers" => $headers);
}
$details = json_decode($responseBody);
if (!$details) {
$message = sprintf("Error while parsing response: %s (#%d)",
PHP_VERSION_ID >= 50500 ? json_last_error_msg() : "Error",
json_last_error());
$details = (object) array(
"message" => $message,
"error" => "ParseError"
);
}
if ($retries > 0 && $status >= 500) continue;
throw Exception::create($details->message, $details->error, $status);
} else {
$message = sprintf("%s (#%d)", curl_error($request), curl_errno($request));
if (PHP_VERSION_ID < 80000) {
curl_close($request);
} else {
unset($request);
}
if ($retries > 0) continue;
throw new ConnectionException("Error while connecting: " . $message);
}
}
}
/**
* @param string|array $headers
* @return array
*/
protected static function parseHeaders($headers) {
if (!is_array($headers)) {
$headers = explode("\r\n", $headers);
}
$res = array();
foreach ($headers as $header) {
if (empty($header)) continue;
$split = explode(":", $header, 2);
if (count($split) === 2) {
$res[strtolower($split[0])] = trim($split[1]);
}
}
return $res;
}
}