-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCUrl.php
619 lines (533 loc) · 17.2 KB
/
CUrl.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
<?php
namespace Modules\Rarv;
use stdClass;
class CUrl
{
/** @var resource $curlObject cURL request */
protected $curlObject = null;
/** @var array $curlOptions Array of cURL options */
protected $curlOptions = array(
'RETURNTRANSFER' => true,
'FAILONERROR' => false,
'FOLLOWLOCATION' => false,
'CONNECTTIMEOUT' => '',
'TIMEOUT' => 30,
'USERAGENT' => '',
'URL' => '',
'POST' => false,
'HTTPHEADER' => array(),
'SSL_VERIFYPEER' => false,
'HEADER' => false,
);
/** @var array $packageOptions Array with options that are not specific to cURL but are used by the package */
protected $packageOptions = array(
'data' => array(),
'files' => array(),
'asJsonRequest' => false,
'asJsonResponse' => false,
'returnAsArray' => false,
'responseObject' => false,
'responseArray' => false,
'enableDebug' => false,
'xDebugSessionName' => '',
'containsFile' => false,
'debugFile' => '',
'saveFile' => '',
);
/**
* Set the URL to which the request is to be sent
*
* @param $url string The URL to which the request is to be sent
* @return Builder
*/
public function to($url)
{
return $this->withCurlOption('URL', $url);
}
/**
* Set the request timeout
*
* @param float $timeout The timeout for the request (in seconds, fractions of a second are okay. Default: 30 seconds)
* @return Builder
*/
public function withTimeout($timeout = 30.0)
{
return $this->withCurlOption('TIMEOUT_MS', ($timeout * 1000));
}
/**
* Add GET or POST data to the request
*
* @param mixed $data Array of data that is to be sent along with the request
* @return Builder
*/
public function withData($data = array())
{
return $this->withPackageOption('data', $data);
}
/**
* Add a file to the request
*
* @param string $key Identifier of the file (how it will be referenced by the server in the $_FILES array)
* @param string $path Full path to the file you want to send
* @param string $mimeType Mime type of the file
* @param string $postFileName Name of the file when sent. Defaults to file name
*
* @return Builder
*/
public function withFile($key, $path, $mimeType = '', $postFileName = '')
{
$fileData = array(
'fileName' => $path,
'mimeType' => $mimeType,
'postFileName' => $postFileName,
);
$this->packageOptions[ 'files' ][ $key ] = $fileData;
return $this->containsFile();
}
/**
* Allow for redirects in the request
*
* @return Builder
*/
public function allowRedirect()
{
return $this->withCurlOption('FOLLOWLOCATION', true);
}
/**
* Configure the package to encode and decode the request data
*
* @param boolean $asArray Indicates whether or not the data should be returned as an array. Default: false
* @return Builder
*/
public function asJson($asArray = false)
{
return $this->asJsonRequest()
->asJsonResponse($asArray);
}
/**
* Configure the package to encode the request data to json before sending it to the server
*
* @return Builder
*/
public function asJsonRequest()
{
return $this->withPackageOption('asJsonRequest', true);
}
/**
* Configure the package to decode the request data from json to object or associative array
*
* @param boolean $asArray Indicates whether or not the data should be returned as an array. Default: false
* @return Builder
*/
public function asJsonResponse($asArray = false)
{
return $this->withPackageOption('asJsonResponse', true)
->withPackageOption('returnAsArray', $asArray);
}
// /**
// * Send the request over a secure connection
// *
// * @return Builder
// */
// public function secure()
// {
// return $this;
// }
/**
* Set any specific cURL option
*
* @param string $key The name of the cURL option
* @param string $value The value to which the option is to be set
* @return Builder
*/
public function withOption($key, $value)
{
return $this->withCurlOption($key, $value);
}
/**
* Set Cookie File
*
* @param string $cookieFile File name to read cookies from
* @return Builder
*/
public function setCookieFile($cookieFile)
{
return $this->withOption('COOKIEFILE', $cookieFile);
}
/**
* Set Cookie Jar
*
* @param string $cookieJar File name to store cookies to
* @return Builder
*/
public function setCookieJar($cookieJar)
{
return $this->withOption('COOKIEJAR', $cookieJar);
}
/**
* Set any specific cURL option
*
* @param string $key The name of the cURL option
* @param string $value The value to which the option is to be set
* @return Builder
*/
protected function withCurlOption($key, $value)
{
$this->curlOptions[ $key ] = $value;
return $this;
}
/**
* Set any specific package option
*
* @param string $key The name of the cURL option
* @param string $value The value to which the option is to be set
* @return Builder
*/
protected function withPackageOption($key, $value)
{
$this->packageOptions[ $key ] = $value;
return $this;
}
/**
* Add a HTTP header to the request
*
* @param string $header The HTTP header that is to be added to the request
* @return Builder
*/
public function withHeader($header)
{
$this->curlOptions[ 'HTTPHEADER' ][] = $header;
return $this;
}
/**
* Add multiple HTTP header at the same time to the request
*
* @param array $headers Array of HTTP headers that must be added to the request
* @return Builder
*/
public function withHeaders(array $headers)
{
$this->curlOptions[ 'HTTPHEADER' ] = array_merge(
$this->curlOptions[ 'HTTPHEADER' ],
$headers
);
return $this;
}
/**
* Add a content type HTTP header to the request
*
* @param string $contentType The content type of the file you would like to download
* @return Builder
*/
public function withContentType($contentType)
{
return $this->withHeader('Content-Type: '. $contentType)
->withHeader('Connection: Keep-Alive');
}
/**
* Add response headers to the response object or response array
*
* @return Builder
*/
public function withResponseHeaders()
{
return $this->withCurlOption('HEADER', true);
}
/**
* Return a full response object with HTTP status and headers instead of only the content
*
* @return Builder
*/
public function returnResponseObject()
{
return $this->withPackageOption('responseObject', true);
}
/**
* Return a full response array with HTTP status and headers instead of only the content
*
* @return Builder
*/
public function returnResponseArray()
{
return $this->withPackageOption('responseArray', true);
}
/**
* Enable debug mode for the cURL request
*
* @param string $logFile The full path to the log file you want to use
* @return Builder
*/
public function enableDebug($logFile)
{
return $this->withPackageOption('enableDebug', true)
->withPackageOption('debugFile', $logFile)
->withOption('VERBOSE', true);
}
/**
* Enable Proxy for the cURL request
*
* @param string $proxy Hostname
* @param string $port Port to be used
* @param string $type Scheme to be used by the proxy
* @param string $username Authentication username
* @param string $password Authentication password
* @return Builder
*/
public function withProxy($proxy, $port = '', $type = '', $username = '', $password = '')
{
$this->withOption('PROXY', $proxy);
if (!empty($port)) {
$this->withOption('PROXYPORT', $port);
}
if (!empty($type)) {
$this->withOption('PROXYTYPE', $type);
}
if (!empty($username) && !empty($password)) {
$this->withOption('PROXYUSERPWD', $username .':'. $password);
}
return $this;
}
/**
* Enable File sending
*
* @return Builder
*/
public function containsFile()
{
return $this->withPackageOption('containsFile', true);
}
/**
* Add the XDebug session name to the request to allow for easy debugging
*
* @param string $sessionName
* @return Builder
*/
public function enableXDebug($sessionName = 'session_1')
{
$this->packageOptions[ 'xDebugSessionName' ] = $sessionName;
return $this;
}
/**
* Send a GET request to a URL using the specified cURL options
*
* @return mixed
*/
public function get()
{
$this->appendDataToURL();
return $this->send();
}
/**
* Send a POST request to a URL using the specified cURL options
*
* @return mixed
*/
public function post()
{
$this->setPostParameters();
return $this->send();
}
/**
* Send a download request to a URL using the specified cURL options
*
* @param string $fileName
* @return mixed
*/
public function download($fileName)
{
$this->packageOptions[ 'saveFile' ] = $fileName;
return $this->send();
}
/**
* Add POST parameters to the curlOptions array
*/
protected function setPostParameters()
{
$this->curlOptions[ 'POST' ] = true;
$parameters = $this->packageOptions[ 'data' ];
if (!empty($this->packageOptions[ 'files' ])) {
foreach ($this->packageOptions[ 'files' ] as $key => $file) {
$parameters[ $key ] = $this->getCurlFileValue($file[ 'fileName' ], $file[ 'mimeType' ], $file[ 'postFileName']);
}
}
if ($this->packageOptions[ 'asJsonRequest' ]) {
$parameters = json_encode($parameters);
}
$this->curlOptions[ 'POSTFIELDS' ] = $parameters;
}
protected function getCurlFileValue($filename, $mimeType, $postFileName)
{
// PHP 5 >= 5.5.0, PHP 7
if (function_exists('curl_file_create')) {
return curl_file_create($filename, $mimeType, $postFileName);
}
// Use the old style if using an older version of PHP
$value = "@{$filename};filename=" . $postFileName;
if ($mimeType) {
$value .= ';type=' . $mimeType;
}
return $value;
}
/**
* Send a PUT request to a URL using the specified cURL options
*
* @return mixed
*/
public function put()
{
$this->setPostParameters();
return $this->withOption('CUSTOMREQUEST', 'PUT')
->send();
}
/**
* Send a PATCH request to a URL using the specified cURL options
*
* @return mixed
*/
public function patch()
{
$this->setPostParameters();
return $this->withOption('CUSTOMREQUEST', 'PATCH')
->send();
}
/**
* Send a DELETE request to a URL using the specified cURL options
*
* @return mixed
*/
public function delete()
{
$this->appendDataToURL();
return $this->withOption('CUSTOMREQUEST', 'DELETE')
->send();
}
/**
* Send the request
*
* @return mixed
*/
protected function send()
{
// Add JSON header if necessary
if ($this->packageOptions[ 'asJsonRequest' ]) {
$this->withHeader('Content-Type: application/json');
}
if ($this->packageOptions[ 'enableDebug' ]) {
$debugFile = fopen($this->packageOptions[ 'debugFile' ], 'w');
$this->withOption('STDERR', $debugFile);
}
// Create the request with all specified options
$this->curlObject = curl_init();
$options = $this->forgeOptions();
curl_setopt_array($this->curlObject, $options);
// Send the request
$response = curl_exec($this->curlObject);
$responseHeader = null;
if ($this->curlOptions[ 'HEADER' ]) {
$headerSize = curl_getinfo($this->curlObject, CURLINFO_HEADER_SIZE);
$responseHeader = substr($response, 0, $headerSize);
$response = substr($response, $headerSize);
}
// Capture additional request information if needed
$responseData = array();
if ($this->packageOptions[ 'responseObject' ] || $this->packageOptions[ 'responseArray' ]) {
$responseData = curl_getinfo($this->curlObject);
if (curl_errno($this->curlObject)) {
$responseData[ 'errorMessage' ] = curl_error($this->curlObject);
}
}
curl_close($this->curlObject);
if ($this->packageOptions[ 'saveFile' ]) {
// Save to file if a filename was specified
$file = fopen($this->packageOptions[ 'saveFile' ], 'w');
fwrite($file, $response);
fclose($file);
} else if ($this->packageOptions[ 'asJsonResponse' ]) {
// Decode the request if necessary
$response = json_decode($response, $this->packageOptions[ 'returnAsArray' ]);
}
if ($this->packageOptions[ 'enableDebug' ]) {
fclose($debugFile);
}
// Return the result
return $this->returnResponse($response, $responseData, $responseHeader);
}
/**
* @param string $headerString Response header string
* @return mixed
*/
protected function parseHeaders($headerString)
{
$headers = array_filter(array_map(function ($x) {
$arr = array_map('trim', explode(':', $x, 2));
if (count($arr) == 2) {
return [ $arr[ 0 ] => $arr[ 1 ] ];
}
}, array_filter(array_map('trim', explode("\r\n", $headerString)))));
return array_collapse($headers);
}
/**
* @param mixed $content Content of the request
* @param array $responseData Additional response information
* @param string $header Response header string
* @return mixed
*/
protected function returnResponse($content, array $responseData = array(), $header = null)
{
if (!$this->packageOptions[ 'responseObject' ] && !$this->packageOptions[ 'responseArray' ]) {
return $content;
}
$object = new stdClass();
$object->content = $content;
$object->status = $responseData[ 'http_code' ];
$object->contentType = $responseData[ 'content_type' ];
if (array_key_exists('errorMessage', $responseData)) {
$object->error = $responseData[ 'errorMessage' ];
}
if ($this->curlOptions[ 'HEADER' ]) {
$object->headers = $this->parseHeaders($header);
}
if ($this->packageOptions[ 'responseObject' ]) {
return $object;
}
if ($this->packageOptions[ 'responseArray' ]) {
return (array) $object;
}
return $content;
}
/**
* Convert the curlOptions to an array of usable options for the cURL request
*
* @return array
*/
protected function forgeOptions()
{
$results = array();
foreach ($this->curlOptions as $key => $value) {
$arrayKey = constant('CURLOPT_' . $key);
if (!$this->packageOptions[ 'containsFile' ] && $key == 'POSTFIELDS' && is_array($value)) {
$results[ $arrayKey ] = http_build_query($value, null, '&');
} else {
$results[ $arrayKey ] = $value;
}
}
if (!empty($this->packageOptions[ 'xDebugSessionName' ])) {
$char = strpos($this->curlOptions[ 'URL' ], '?') ? '&' : '?';
$this->curlOptions[ 'URL' ] .= $char . 'XDEBUG_SESSION_START='. $this->packageOptions[ 'xDebugSessionName' ];
}
return $results;
}
/**
* Append set data to the query string for GET and DELETE cURL requests
*
* @return string
*/
protected function appendDataToURL()
{
$parameterString = '';
if (is_array($this->packageOptions[ 'data' ]) && count($this->packageOptions[ 'data' ]) != 0) {
$parameterString = '?'. http_build_query($this->packageOptions[ 'data' ], null, '&');
}
return $this->curlOptions[ 'URL' ] .= $parameterString;
}
}