/
Request.php
298 lines (270 loc) · 9.16 KB
/
Request.php
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
<?php
namespace Lucinda\URL;
use Lucinda\URL\Connection\Single as Connection;
use Lucinda\URL\Request\Exception as RequestException;
use Lucinda\URL\Response\Exception as ResponseException;
use Lucinda\URL\Request\Headers;
use Lucinda\URL\Request\SSL;
use Lucinda\URL\Request\Method;
use Lucinda\URL\Request\Parameters;
/**
* Encapsulates a GET HTTP/HTTPS request for any resource
*
* TODO: add support for curl_copy_handle
*/
class Request
{
protected const COVERED_OPTIONS = [
CURLOPT_URL=>"setURL",
CURLOPT_POST=>"setMethod",
CURLOPT_NOBODY=>"setMethod",
CURLOPT_CUSTOMREQUEST=>"setMethod",
CURLOPT_COOKIESESSION=>"setCookies",
CURLOPT_COOKIEFILE=>"setCookies",
CURLOPT_COOKIEJAR=>"setCookies",
CURLOPT_COOKIELIST=>"setCookies",
CURLOPT_TIMECONDITION=>"setHeaders",
CURLOPT_TIMEVALUE=>"setHeaders",
CURLOPT_USERAGENT=>"setHeaders",
CURLOPT_REFERER=>"setHeaders",
CURLOPT_COOKIE=>"setHeaders",
CURLOPT_HTTPHEADER=>"setHeaders",
CURLOPT_POSTFIELDS=>"setParameters",
CURLOPT_CAINFO=>"setSSL",
CURLOPT_SSL_VERIFYPEER=>"setSSL",
CURLOPT_SSL_VERIFYHOST=>"setSSL",
CURLOPT_SSLCERT=>"setSSL",
CURLOPT_SSLKEY=>"setSSL",
CURLOPT_FOLLOWLOCATION=>"prepare",
CURLOPT_HEADERFUNCTION=>"execute",
CURLOPT_MAXREDIRS=>"prepare",
CURLOPT_RETURNTRANSFER=>"prepare",
CURLOPT_CONNECTTIMEOUT_MS=>"prepare"
];
protected string $url = "";
protected Method $method = Method::GET;
protected bool $isSSL = false;
protected bool $isPOST = false;
protected bool $returnTransfer = true;
protected Connection $connection;
/**
* Initiates a new URL connection or imports existing cURL handler
*
* @param ?string $url
* @throws RequestException
*/
public function __construct(?string $url = null)
{
$this->connection = new Connection();
if ($url) {
$this->setURL($url);
}
}
/**
* Sets URL of requested resource
*
* @param string $url
* @throws RequestException If URL is invalid
*/
public function setURL(string $url): void
{
if (!filter_var($url, FILTER_VALIDATE_URL)) {
throw new RequestException("URL is invalid: ".$url);
}
$this->connection->setOption(CURLOPT_URL, $url);
$this->url = $url;
}
/**
* Sets HTTP method to use in requesting resource. If not set, GET is used by default!
*
* @param Method $method One of enum values (eg: Method::POST)
*/
public function setMethod(Method $method): void
{
switch ($method) {
case Method::GET:
// do nothing
break;
case Method::POST:
$this->connection->setOption(CURLOPT_POST, true);
break;
case Method::HEAD:
$this->connection->setOption(CURLOPT_NOBODY, true);
break;
default:
$this->connection->setOption(CURLOPT_CUSTOMREQUEST, $method->value);
break;
}
$this->method = $method;
}
/**
* Sets parameters to send in POST requests through Parameters object returned.
*
* @param array<string,mixed> $parameters Optional key-value set of POST parameters to send already.
* @return Parameters
*/
public function setParameters(array $parameters = []): Parameters
{
$this->isPOST = true;
return new Parameters($this->connection, $parameters);
}
/**
* Sets raw (binary) content to be uploaded using POST
*
* @param string $body
*/
public function setRaw(string $body): void
{
$this->isPOST = true;
$this->connection->setOption(CURLOPT_POSTFIELDS, $body);
}
/**
* Sets HTTP headers to send through Headers object returned.
*
* @return Headers
*/
public function setHeaders(): Headers
{
return new Headers($this->connection);
}
/**
* Sets SQL policy through SSL object returned.
*
* @param string $certificateAuthorityBundlePath
* @return SSL
* @throws FileNotFoundException
*/
public function setSSL(string $certificateAuthorityBundlePath): SSL
{
$this->isSSL = true;
return new SSL($this->connection, $certificateAuthorityBundlePath);
}
/**
* Sets obscure CURLOPT not already covered by API.
*
* @param int $curlopt Curlopt option key (eg: CURLOPT_PRIVATE)
* @param mixed $value
* @throws RequestException If option already covered
*/
public function setCustomOption(int $curlopt, mixed $value): void
{
if (isset(self::COVERED_OPTIONS[$curlopt])) {
throw new RequestException("Option already covered by ".self::COVERED_OPTIONS[$curlopt]." method!");
}
$this->connection->setOption($curlopt, $value);
}
/**
* Sets whether transfer should be returned (default is YES)
*
* @param bool $returnTransfer
* @return void
*/
public function setReturnTransfer(bool $returnTransfer): void
{
$this->returnTransfer = $returnTransfer;
}
/**
* Gets connection object inside
*
* @return Connection
*/
public function getConnection(): Connection
{
return $this->connection;
}
/**
* Gets path to default (API-defined) certificate bundle
*
* @return string
*/
protected function getDefaultCertificatePath(): string
{
return dirname(__DIR__).DIRECTORY_SEPARATOR."certificates".DIRECTORY_SEPARATOR."cacert.pem";
}
/**
* Validates request and prepares it for being sent. Called already by "execute" method!
*
* @param int $maxRedirectionsAllowed
* @param int $timeout
* @return void
* @throws FileNotFoundException
* @throws RequestException
*/
public function prepare(int $maxRedirectionsAllowed = 0, int $timeout = 300000): void
{
$this->validate();
if (str_starts_with($this->url, "https") && !$this->isSSL) {
$this->setSSL($this->getDefaultCertificatePath());
}
// sets redirection policy
if ($maxRedirectionsAllowed==0) {
$this->connection->setOption(CURLOPT_FOLLOWLOCATION, false);
} else {
$this->connection->setOption(CURLOPT_FOLLOWLOCATION, true);
$this->connection->setOption(CURLOPT_MAXREDIRS, $maxRedirectionsAllowed);
}
// sets return transfer
$this->connection->setOption(CURLOPT_RETURNTRANSFER, $this->returnTransfer);
// sets connection timeout
$this->connection->setOption(CURLOPT_CONNECTTIMEOUT_MS, $timeout);
}
/**
* Validates request and throws exception when information inside is wrong or insufficient
*
* @return void
* @throws RequestException
*/
protected function validate(): void
{
// validate url
if (!$this->url) {
throw new RequestException("Setting a URL is mandatory!");
}
// validate POST parameters
if ($this->method == Method::POST && !$this->isPOST) {
throw new RequestException("No parameters to POST!");
}
if (!in_array($this->method, [Method::POST, Method::PUT, Method::DELETE]) && $this->isPOST) {
throw new RequestException("Parameters can't be used unless request method is POST");
}
// validate SSL and sets certificate if missing
if (!str_starts_with($this->url, "https") && $this->isSSL) {
throw new RequestException("URL requested doesn't require SSL!");
}
}
/**
* Validates request then executes it in order to produce a response
*
* @param int $maxRedirectionsAllowed Maximum number of redirections allowed (if zero, it means none are)
* @param int $timeout Connection timeout in milliseconds
* @throws ResponseException|RequestException|FileNotFoundException If execution failed
* @return Response
*/
public function execute(int $maxRedirectionsAllowed = 0, int $timeout = 300000): Response
{
// validates request and prepares it for being sent
$this->prepare($maxRedirectionsAllowed, $timeout);
// registers response header processing
$headers = [];
if ($this->returnTransfer) {
$this->connection->setOption(
CURLOPT_HEADERFUNCTION,
function ($curl, $header) use (&$headers) {
$position = strpos($header, ":");
if ($position !== false) {
$name = ucwords(trim(substr($header, 0, $position)), "-");
$value = trim(substr($header, $position+1));
$headers[$name] = $value;
}
return strlen($header);
}
);
}
// executes request
$startTime = microtime(true);
$body = $this->connection->execute();
$endTime = microtime(true);
// split headers from body
return new Response($this->connection, $body, $headers, ($endTime-$startTime));
}
}