-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPlug.php
More file actions
619 lines (547 loc) · 19.7 KB
/
Plug.php
File metadata and controls
619 lines (547 loc) · 19.7 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
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 declare(strict_types=1);
/**
* HyperPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace modethirteen\Http;
use Closure;
use InvalidArgumentException;
use modethirteen\Http\Content\FileContent;
use modethirteen\Http\Content\IContent;
use modethirteen\Http\Exception\MalformedPathQueryFragmentException;
use modethirteen\Http\Exception\NotImplementedException;
use modethirteen\Http\Exception\PlugUriHostRequiredException;
use modethirteen\Http\Exception\ResultParserContentExceedsMaxContentLengthException;
use modethirteen\Http\Mock\MockPlug;
use modethirteen\Http\Mock\MockRequestMatcher;
use modethirteen\Http\Parser\IResultParser;
/**
* Class Plug - builder and invocation for simple HTTP requests
*
* @package modethirteen\Http
*/
class Plug {
const DEFAULT_MAX_AUTO_REDIRECTS = 10;
const METHOD_DELETE = 'DELETE';
const METHOD_GET = 'GET';
const METHOD_HEAD = 'HEAD';
const METHOD_POST = 'POST';
const METHOD_PUT = 'PUT';
/**
* @var int
*/
protected int $maxAutoRedirects = self::DEFAULT_MAX_AUTO_REDIRECTS;
/**
* @var array<Closure>
*/
protected array $preInvokeRequestCallbacks = [];
/**
* @var array<Closure>
*/
protected array $postInvokeCallbacks = [];
/**
* @var IResultParser[]
*/
protected array $parsers = [];
/**
* @var string|null - username for basic auth credentials
*/
protected ?string $user = null;
/**
* @var string|null - password for basic auth credentials
*/
protected ?string $password = null;
/**
* @var IMutableHeaders - stores the headers for the request
*/
protected IMutableHeaders $headers;
/**
* @var int $timeout - sets the request timeout length (s)
*/
protected int $timeout = 300;
/**
* @var XUri
*/
protected XUri $uri;
/**
* @param XUri $uri - target uri
* @throws PlugUriHostRequiredException
*/
public function __construct(XUri $uri) {
$this->headers = new Headers();
if(StringUtil::isNullOrEmpty($uri->getHost())) {
throw new PlugUriHostRequiredException($uri);
}
$this->uri = $uri;
}
public function __clone() {
// deep copy internal data objects and arrays
$this->headers = unserialize(serialize($this->headers));
$this->uri = unserialize(serialize($this->uri));
}
#region Plug request data accessors
/**
* Retrieves HTTP headers
*
* @return IHeaders
*/
public function getHeaders() : IHeaders {
return $this->headers;
}
/**
* Retrieves the fully qualified uri
*
* @param bool $includeCredentials - if true, any set username and password will be included
* @return XUri
*/
public function getUri(bool $includeCredentials = false) : XUri {
$uri = clone $this->uri;
// @note user & password are passed via Authorization headers when invoked, see #invokeApplyCredentials
if($includeCredentials) {
$uri = $uri->withUserInfo($this->user, $this->password);
}
return $uri;
}
/**
* Retrieves the number of seconds before invocation will fail due to timeout
*
* @return int
*/
public function getTimeout() : int {
return $this->timeout;
}
/**
* Retrieves the maximum number of redirects to follow before giving up
*
* @return int
*/
public function getMaxAutoRedirects() : int {
return $this->maxAutoRedirects;
}
/**
* Will this plug automatically follow redirects (301, 302, 307)?
*
* @return bool
*/
public function isAutoRedirectEnabled() : bool {
return $this->maxAutoRedirects > 0;
}
#endregion
#region Plug request builders
/**
* Return an instance with the specified result parser
*
* @param IResultParser $parser
* @return static
*/
public function withResultParser(IResultParser $parser) : object {
$plug = clone $this;
$plug->setResultParser($parser);
return $plug;
}
/**
* Return an instance with the added header value
*
* @param string $name - case-insensitive header field name to add
* @param mixed $value - header value
* @return static
*/
public function withAddedHeader(string $name, $value) : object {
$plug = clone $this;
$plug->headers->addHeader($name, $value);
return $plug;
}
/**
* Return an instance with the set or replaced header value
*
* @param string $name - case-insensitive header field name
* @param mixed $value - header value
* @return static
*/
public function withHeader(string $name, $value) : object {
$plug = clone $this;
$plug->headers->setHeader($name, $value);
return $plug;
}
/**
* Return an instance without the specified header
*
* @param string $name - case-insensitive header field name to remove
* @return static
*/
public function withoutHeader(string $name) : object {
$plug = clone $this;
$plug->headers->removeHeader($name);
return $plug;
}
/**
* Return an instance with the provided URI
*
* @link http://tools.ietf.org/html/rfc3986#section-4.3
* @param XUri $uri - new request URI to use
* @param bool $preserveHost - preserve the original state of the Host header
* @return static
*/
public function withUri(XUri $uri, bool $preserveHost = false) : object {
$plug = clone $this;
$host = StringUtil::stringify($plug->uri->getHost());
$plug->uri = $uri;
if($preserveHost) {
$plug->uri = $plug->uri->withHost($host);
}
return $plug;
}
/**
* Return an instance with appended path segments
*
* @param mixed ...$segments - path segments to add to the request (ex: $this->at('foo', 'bar', 'baz'))
* @return static
* @throws MalformedPathQueryFragmentException
*/
public function at(...$segments) : object {
$plug = clone $this;
$path = '';
foreach($segments as $segment) {
$path .= '/' . ltrim(StringUtil::stringify($segment), '/');
}
$plug->uri = $plug->uri->atPath($path);
return $plug;
}
/**
* Return an instance with query string GET variables appended
*
* @param string $name - variable name
* @param mixed $value - variable value
* @return static
*/
public function with(string $name, $value) : object {
$plug = clone $this;
$plug->uri = $value !== null
? $plug->uri->withQueryParam($name, $value)
: $plug->uri->withoutQueryParam($name);
return $plug;
}
/**
* Return an instance with standard HTTP auth credentials for the request
*
* @param string $user - user name to use for authorization
* @param string|null $password - optional password
* @return static
*/
public function withCredentials(string $user, ?string $password) : object {
$plug = clone $this;
$plug->user = $user;
$plug->password = $password;
return $plug;
}
/**
* Return an instance with the specified request timeout (ms)
*
* @param int $timeout
* @return static
*/
public function withTimeout(int $timeout) : object {
$plug = clone $this;
$plug->timeout = $timeout;
return $plug;
}
/**
* Return an instance that calls the supplied callback with the request before invocation
* Multiple callbacks can be added, and are executed in the order they were added
*
* @param Closure $callback - $callback(string $method, XUri $uri, IMutableHeaders $headers, IContent $content) : void
* @return static
*/
public function withPreInvokeCallback(Closure $callback) : object {
$plug = clone $this;
$plug->preInvokeRequestCallbacks[] = $callback;
return $plug;
}
/**
* Return an instance that calls the supplied callback with the Result instance after invocation
* Multiple callbacks can be added, and are executed in the order they were added
*
* @param Closure $callback - $callback(Result $result) : void
* @return static
*/
public function withPostInvokeCallback(Closure $callback) : object {
$plug = clone $this;
$plug->postInvokeCallbacks[] = $callback;
return $plug;
}
/**
* Return an instance with auto redirect behavior with the specified number of redirects
*
* @param int $maxAutoRedirects - maximum number of redirects to follow, 0 if no redirects should be followed
* @return static
*/
public function withAutoRedirects(int $maxAutoRedirects = self::DEFAULT_MAX_AUTO_REDIRECTS) : object {
$plug = clone $this;
$plug->maxAutoRedirects = $maxAutoRedirects;
return $plug;
}
#endregion
#region Plug request invocation
/**
* Performs a GET request
*
* @return Result
* @throws ResultParserContentExceedsMaxContentLengthException
*/
public function get() : object {
return $this->invoke(self::METHOD_GET);
}
/**
* Performs a HEAD request
*
* @return Result
* @throws ResultParserContentExceedsMaxContentLengthException
*/
public function head() : object {
return $this->invoke(self::METHOD_HEAD);
}
/**
* Performs a POST request
*
* @param IContent|null $content - optionally send a content body with the request
* @return Result
* @throws ResultParserContentExceedsMaxContentLengthException
* @throws InvalidArgumentException
*/
public function post(IContent $content = null) : object {
return $this->invoke(self::METHOD_POST, $content);
}
/**
* Performs a PUT request
*
* @param IContent|null $content - optionally send a content body with the request
* @return Result
* @throws ResultParserContentExceedsMaxContentLengthException
* @throws NotImplementedException
*/
public function put(IContent $content = null) : object {
if($content !== null && !($content instanceof FileContent)) {
// TODO (modethirteen, 20180422): handle PUT content that is not file content
throw new NotImplementedException();
}
return $this->invoke(self::METHOD_PUT, $content);
}
/**
* Performs a DELETE request
*
* @return Result
* @throws ResultParserContentExceedsMaxContentLengthException
*/
public function delete() : object {
return $this->invoke(self::METHOD_DELETE);
}
#endregion
#region Common helpers
/**
* @param string $method
* @param IContent|null $content
* @return Result
* @throws ResultParserContentExceedsMaxContentLengthException
*/
protected function invoke(string $method, IContent $content = null) : object {
$requestUri = $this->getUri();
$requestHeaders = clone $this->headers;
$this->invokeApplyCredentials($requestHeaders);
foreach($this->preInvokeRequestCallbacks as $callback) {
// mutate request settings with callback
$callback($method, $requestUri, $requestHeaders, $content);
}
return $this->invokeRequest($method, $requestUri, $requestHeaders, $content);
}
/**
* @param IMutableHeaders $headers
* @return void
*/
protected function invokeApplyCredentials(IMutableHeaders $headers) : void {
// apply manually given credentials
if($this->user !== null || $this->password !== null) {
$headers->addHeader(Headers::HEADER_AUTHORIZATION, 'Basic ' . base64_encode($this->user . ':' . $this->password));
}
}
/**
* Return the formatted invocation result
*
* @param Result $result
* @return Result
* @throws ResultParserContentExceedsMaxContentLengthException
*/
protected function invokeComplete(Result $result) : object {
foreach($this->parsers as $parser) {
$result = $parser->toParsedResult($result);
}
foreach($this->postInvokeCallbacks as $callback) {
// mutate result instance with callback
$callback($result);
}
return $result;
}
/**
* @param string $method
* @param XUri $requestUri
* @param IMutableHeaders $requestHeaders
* @param IContent|null $content
* @return Result
* @throws ResultParserContentExceedsMaxContentLengthException
*/
protected function invokeRequest(string $method, XUri $requestUri, IMutableHeaders $requestHeaders, ?IContent $content) : object {
$requestStart = 0;
$requestEnd = 0;
// handle content data
$filePath = null;
$body = null;
if($content !== null) {
if($content instanceof FileContent) {
$filePath = $content->toRaw();
} else {
$body = $content->toRaw();
// explicitly set content length 0 if string content is empty
if(is_string($body) && StringUtil::isNullOrEmpty($body)) {
$requestHeaders->setHeader(Headers::HEADER_CONTENT_LENGTH, '0');
}
}
// set the content type if provided
$contentType = $content->getContentType();
if($contentType !== null && !StringUtil::isNullOrEmpty($contentType->toString())) {
$requestHeaders->setHeader(Headers::HEADER_CONTENT_TYPE, $contentType->toString());
}
} else {
$requestHeaders->setHeader(Headers::HEADER_CONTENT_LENGTH, '0');
}
// if MockPlug returns a response, curl is not needed
if(MockPlug::$isRegistered && $filePath === null) {
$matcher = (new MockRequestMatcher($method, $requestUri))
->withHeaders($requestHeaders)
->withBody($body);
$result = MockPlug::getResult($matcher);
if($result !== null) {
return $this->invokeComplete($result->withRequestInfo($method, $requestUri, $requestHeaders, $requestStart, $requestEnd));
}
}
// normal plug request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $requestUri->toString());
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, $this->getTimeout());
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, $this->isAutoRedirectEnabled());
curl_setopt($curl, CURLOPT_MAXREDIRS, $this->getMaxAutoRedirects());
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
// add the request headers
if(!$requestHeaders->isEmpty()) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $requestHeaders->toRawHeaders());
}
// retrieve the response headers
$responseHeaders = new Headers();
$rawResponseHeaders = [];
curl_setopt($curl, CURLOPT_HEADERFUNCTION, function(
/** @noinspection PhpUnusedParameterInspection */
$curl,
$header
) use (&$responseHeaders, &$rawResponseHeaders) {
$length = strlen($header);
$header = trim($header);
if(!StringUtil::isNullOrEmpty($header)) {
$rawResponseHeaders[] = $header;
}
if(StringUtil::startsWithInvariantCase($header, 'HTTP/1.1')) {
// status code means new http message section, we only care out the last section
// for operational concerns so reset headers except for set-cookies
$setCookieValues = $responseHeaders->getHeader(Headers::HEADER_SET_COOKIE);
$responseHeaders = new Headers();
foreach($setCookieValues as $setCookieValue) {
$responseHeaders->addHeader(Headers::HEADER_SET_COOKIE, $setCookieValue);
}
return $length;
} else {
try {
$responseHeaders->addRawHeader($header);
} catch(InvalidArgumentException $e) {
// TODO (modethirteen, 20180424): add a handler for invalid http headers
}
}
return $length;
});
// custom behavior based on the request type
switch($method) {
case self::METHOD_PUT:
if($filePath !== null) {
// read in content from file
curl_setopt($curl, CURLOPT_PUT, true);
curl_setopt($curl, CURLOPT_INFILE, fopen($filePath, 'r'));
curl_setopt($curl, CURLOPT_INFILESIZE, filesize($filePath));
}
// TODO (modethirteen, 20180422): handle PUT content that is not file content
break;
case self::METHOD_POST:
if($filePath !== null) {
// POST a file without using multipart upload (required for some API's)
// to POST a file with multipart upload, use FormDataContent::withFileContent()
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_UPLOAD, true);
curl_setopt($curl, CURLOPT_INFILE, fopen($filePath, 'r'));
curl_setopt($curl, CURLOPT_INFILESIZE, filesize($filePath));
} else {
/**
* The full data to post in a HTTP "POST" operation.
* This can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as
* key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.
*/
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
}
break;
default:
}
// execute request
$requestStart = $this->getTime();
$httpMessage = curl_exec($curl);
$requestEnd = $this->getTime();
// create the result
$type = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);
$data = [
'rawheaders' => $rawResponseHeaders,
'type' => is_string($type) ? $type : null,
'errno' => curl_errno($curl),
'error' => curl_error($curl)
];
$result = (new Result($data))
->withStatus(curl_getinfo($curl, CURLINFO_HTTP_CODE))
->withHeaders($responseHeaders)
->withRequestInfo($method, $requestUri, $requestHeaders, $requestStart, $requestEnd);
if(!is_bool($httpMessage) && !StringUtil::isNullOrEmpty($httpMessage)) {
$result = $result->withBody($httpMessage);
}
curl_close($curl);
return $this->invokeComplete($result);
}
/**
* @param IResultParser $parser
* @return void
*/
protected function setResultParser(IResultParser $parser) : void {
$this->parsers[get_class($parser)] = $parser;
}
/**
* @return float
*/
private function getTime() : float {
$st = explode(' ', microtime());
return (float)$st[0] + (float)$st[1];
}
#endregion
}