PendingRequest.php
28.4 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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
<?php
namespace Illuminate\Http\Client;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\TransferException;
use GuzzleHttp\HandlerStack;
use Illuminate\Http\Client\Events\ConnectionFailed;
use Illuminate\Http\Client\Events\RequestSending;
use Illuminate\Http\Client\Events\ResponseReceived;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Conditionable;
use Illuminate\Support\Traits\Macroable;
use Psr\Http\Message\MessageInterface;
use Psr\Http\Message\RequestInterface;
use Symfony\Component\VarDumper\VarDumper;
class PendingRequest
{
use Conditionable, Macroable;
/**
* The factory instance.
*
* @var \Illuminate\Http\Client\Factory|null
*/
protected $factory;
/**
* The Guzzle client instance.
*
* @var \GuzzleHttp\Client
*/
protected $client;
/**
* The base URL for the request.
*
* @var string
*/
protected $baseUrl = '';
/**
* The request body format.
*
* @var string
*/
protected $bodyFormat;
/**
* The raw body for the request.
*
* @var string
*/
protected $pendingBody;
/**
* The pending files for the request.
*
* @var array
*/
protected $pendingFiles = [];
/**
* The request cookies.
*
* @var array
*/
protected $cookies;
/**
* The transfer stats for the request.
*
* \GuzzleHttp\TransferStats
*/
protected $transferStats;
/**
* The request options.
*
* @var array
*/
protected $options = [];
/**
* The number of times to try the request.
*
* @var int
*/
protected $tries = 1;
/**
* The number of milliseconds to wait between retries.
*
* @var int
*/
protected $retryDelay = 100;
/**
* The callback that will determine if the request should be retried.
*
* @var callable|null
*/
protected $retryWhenCallback = null;
/**
* The callbacks that should execute before the request is sent.
*
* @var \Illuminate\Support\Collection
*/
protected $beforeSendingCallbacks;
/**
* The stub callables that will handle requests.
*
* @var \Illuminate\Support\Collection|null
*/
protected $stubCallbacks;
/**
* The middleware callables added by users that will handle requests.
*
* @var \Illuminate\Support\Collection
*/
protected $middleware;
/**
* Whether the requests should be asynchronous.
*
* @var bool
*/
protected $async = false;
/**
* The pending request promise.
*
* @var \GuzzleHttp\Promise\PromiseInterface
*/
protected $promise;
/**
* The sent request object, if a request has been made.
*
* @var \Illuminate\Http\Client\Request|null
*/
protected $request;
/**
* The Guzzle request options that are mergable via array_merge_recursive.
*
* @var array
*/
protected $mergableOptions = [
'cookies',
'form_params',
'headers',
'json',
'multipart',
'query',
];
/**
* Create a new HTTP Client instance.
*
* @param \Illuminate\Http\Client\Factory|null $factory
* @return void
*/
public function __construct(Factory $factory = null)
{
$this->factory = $factory;
$this->middleware = new Collection;
$this->asJson();
$this->options = [
'http_errors' => false,
];
$this->beforeSendingCallbacks = collect([function (Request $request, array $options, PendingRequest $pendingRequest) {
$pendingRequest->request = $request;
$pendingRequest->cookies = $options['cookies'];
$pendingRequest->dispatchRequestSendingEvent();
}]);
}
/**
* Set the base URL for the pending request.
*
* @param string $url
* @return $this
*/
public function baseUrl(string $url)
{
$this->baseUrl = $url;
return $this;
}
/**
* Attach a raw body to the request.
*
* @param string $content
* @param string $contentType
* @return $this
*/
public function withBody($content, $contentType)
{
$this->bodyFormat('body');
$this->pendingBody = $content;
$this->contentType($contentType);
return $this;
}
/**
* Indicate the request contains JSON.
*
* @return $this
*/
public function asJson()
{
return $this->bodyFormat('json')->contentType('application/json');
}
/**
* Indicate the request contains form parameters.
*
* @return $this
*/
public function asForm()
{
return $this->bodyFormat('form_params')->contentType('application/x-www-form-urlencoded');
}
/**
* Attach a file to the request.
*
* @param string|array $name
* @param string|resource $contents
* @param string|null $filename
* @param array $headers
* @return $this
*/
public function attach($name, $contents = '', $filename = null, array $headers = [])
{
if (is_array($name)) {
foreach ($name as $file) {
$this->attach(...$file);
}
return $this;
}
$this->asMultipart();
$this->pendingFiles[] = array_filter([
'name' => $name,
'contents' => $contents,
'headers' => $headers,
'filename' => $filename,
]);
return $this;
}
/**
* Indicate the request is a multi-part form request.
*
* @return $this
*/
public function asMultipart()
{
return $this->bodyFormat('multipart');
}
/**
* Specify the body format of the request.
*
* @param string $format
* @return $this
*/
public function bodyFormat(string $format)
{
return tap($this, function ($request) use ($format) {
$this->bodyFormat = $format;
});
}
/**
* Specify the request's content type.
*
* @param string $contentType
* @return $this
*/
public function contentType(string $contentType)
{
return $this->withHeaders(['Content-Type' => $contentType]);
}
/**
* Indicate that JSON should be returned by the server.
*
* @return $this
*/
public function acceptJson()
{
return $this->accept('application/json');
}
/**
* Indicate the type of content that should be returned by the server.
*
* @param string $contentType
* @return $this
*/
public function accept($contentType)
{
return $this->withHeaders(['Accept' => $contentType]);
}
/**
* Add the given headers to the request.
*
* @param array $headers
* @return $this
*/
public function withHeaders(array $headers)
{
return tap($this, function ($request) use ($headers) {
return $this->options = array_merge_recursive($this->options, [
'headers' => $headers,
]);
});
}
/**
* Specify the basic authentication username and password for the request.
*
* @param string $username
* @param string $password
* @return $this
*/
public function withBasicAuth(string $username, string $password)
{
return tap($this, function ($request) use ($username, $password) {
return $this->options['auth'] = [$username, $password];
});
}
/**
* Specify the digest authentication username and password for the request.
*
* @param string $username
* @param string $password
* @return $this
*/
public function withDigestAuth($username, $password)
{
return tap($this, function ($request) use ($username, $password) {
return $this->options['auth'] = [$username, $password, 'digest'];
});
}
/**
* Specify an authorization token for the request.
*
* @param string $token
* @param string $type
* @return $this
*/
public function withToken($token, $type = 'Bearer')
{
return tap($this, function ($request) use ($token, $type) {
return $this->options['headers']['Authorization'] = trim($type.' '.$token);
});
}
/**
* Specify the user agent for the request.
*
* @param string $userAgent
* @return $this
*/
public function withUserAgent($userAgent)
{
return tap($this, function ($request) use ($userAgent) {
return $this->options['headers']['User-Agent'] = trim($userAgent);
});
}
/**
* Specify the cookies that should be included with the request.
*
* @param array $cookies
* @param string $domain
* @return $this
*/
public function withCookies(array $cookies, string $domain)
{
return tap($this, function ($request) use ($cookies, $domain) {
return $this->options = array_merge_recursive($this->options, [
'cookies' => CookieJar::fromArray($cookies, $domain),
]);
});
}
/**
* Indicate that redirects should not be followed.
*
* @return $this
*/
public function withoutRedirecting()
{
return tap($this, function ($request) {
return $this->options['allow_redirects'] = false;
});
}
/**
* Indicate that TLS certificates should not be verified.
*
* @return $this
*/
public function withoutVerifying()
{
return tap($this, function ($request) {
return $this->options['verify'] = false;
});
}
/**
* Specify the path where the body of the response should be stored.
*
* @param string|resource $to
* @return $this
*/
public function sink($to)
{
return tap($this, function ($request) use ($to) {
return $this->options['sink'] = $to;
});
}
/**
* Specify the timeout (in seconds) for the request.
*
* @param int $seconds
* @return $this
*/
public function timeout(int $seconds)
{
return tap($this, function () use ($seconds) {
$this->options['timeout'] = $seconds;
});
}
/**
* Specify the number of times the request should be attempted.
*
* @param int $times
* @param int $sleep
* @param callable|null $when
* @return $this
*/
public function retry(int $times, int $sleep = 0, ?callable $when = null)
{
$this->tries = $times;
$this->retryDelay = $sleep;
$this->retryWhenCallback = $when;
return $this;
}
/**
* Replace the specified options on the request.
*
* @param array $options
* @return $this
*/
public function withOptions(array $options)
{
return tap($this, function ($request) use ($options) {
return $this->options = array_replace_recursive(
array_merge_recursive($this->options, Arr::only($options, $this->mergableOptions)),
$options
);
});
}
/**
* Add new middleware the client handler stack.
*
* @param callable $middleware
* @return $this
*/
public function withMiddleware(callable $middleware)
{
$this->middleware->push($middleware);
return $this;
}
/**
* Add a new "before sending" callback to the request.
*
* @param callable $callback
* @return $this
*/
public function beforeSending($callback)
{
return tap($this, function () use ($callback) {
$this->beforeSendingCallbacks[] = $callback;
});
}
/**
* Dump the request before sending.
*
* @return $this
*/
public function dump()
{
$values = func_get_args();
return $this->beforeSending(function (Request $request, array $options) use ($values) {
foreach (array_merge($values, [$request, $options]) as $value) {
VarDumper::dump($value);
}
});
}
/**
* Dump the request before sending and end the script.
*
* @return $this
*/
public function dd()
{
$values = func_get_args();
return $this->beforeSending(function (Request $request, array $options) use ($values) {
foreach (array_merge($values, [$request, $options]) as $value) {
VarDumper::dump($value);
}
exit(1);
});
}
/**
* Issue a GET request to the given URL.
*
* @param string $url
* @param array|string|null $query
* @return \Illuminate\Http\Client\Response
*/
public function get(string $url, $query = null)
{
return $this->send('GET', $url, func_num_args() === 1 ? [] : [
'query' => $query,
]);
}
/**
* Issue a HEAD request to the given URL.
*
* @param string $url
* @param array|string|null $query
* @return \Illuminate\Http\Client\Response
*/
public function head(string $url, $query = null)
{
return $this->send('HEAD', $url, func_num_args() === 1 ? [] : [
'query' => $query,
]);
}
/**
* Issue a POST request to the given URL.
*
* @param string $url
* @param array $data
* @return \Illuminate\Http\Client\Response
*/
public function post(string $url, array $data = [])
{
return $this->send('POST', $url, [
$this->bodyFormat => $data,
]);
}
/**
* Issue a PATCH request to the given URL.
*
* @param string $url
* @param array $data
* @return \Illuminate\Http\Client\Response
*/
public function patch($url, $data = [])
{
return $this->send('PATCH', $url, [
$this->bodyFormat => $data,
]);
}
/**
* Issue a PUT request to the given URL.
*
* @param string $url
* @param array $data
* @return \Illuminate\Http\Client\Response
*/
public function put($url, $data = [])
{
return $this->send('PUT', $url, [
$this->bodyFormat => $data,
]);
}
/**
* Issue a DELETE request to the given URL.
*
* @param string $url
* @param array $data
* @return \Illuminate\Http\Client\Response
*/
public function delete($url, $data = [])
{
return $this->send('DELETE', $url, empty($data) ? [] : [
$this->bodyFormat => $data,
]);
}
/**
* Send a pool of asynchronous requests concurrently.
*
* @param callable $callback
* @return array
*/
public function pool(callable $callback)
{
$results = [];
$requests = tap(new Pool($this->factory), $callback)->getRequests();
foreach ($requests as $key => $item) {
$results[$key] = $item instanceof static ? $item->getPromise()->wait() : $item->wait();
}
return $results;
}
/**
* Send the request to the given URL.
*
* @param string $method
* @param string $url
* @param array $options
* @return \Illuminate\Http\Client\Response
*
* @throws \Exception
*/
public function send(string $method, string $url, array $options = [])
{
$url = ltrim(rtrim($this->baseUrl, '/').'/'.ltrim($url, '/'), '/');
if (isset($options[$this->bodyFormat])) {
if ($this->bodyFormat === 'multipart') {
$options[$this->bodyFormat] = $this->parseMultipartBodyFormat($options[$this->bodyFormat]);
} elseif ($this->bodyFormat === 'body') {
$options[$this->bodyFormat] = $this->pendingBody;
}
if (is_array($options[$this->bodyFormat])) {
$options[$this->bodyFormat] = array_merge(
$options[$this->bodyFormat], $this->pendingFiles
);
}
} else {
$options[$this->bodyFormat] = $this->pendingBody;
}
[$this->pendingBody, $this->pendingFiles] = [null, []];
if ($this->async) {
return $this->makePromise($method, $url, $options);
}
return retry($this->tries ?? 1, function () use ($method, $url, $options) {
try {
return tap(new Response($this->sendRequest($method, $url, $options)), function ($response) {
$this->populateResponse($response);
if ($this->tries > 1 && ! $response->successful()) {
$response->throw();
}
$this->dispatchResponseReceivedEvent($response);
});
} catch (ConnectException $e) {
$this->dispatchConnectionFailedEvent();
throw new ConnectionException($e->getMessage(), 0, $e);
}
}, $this->retryDelay ?? 100, $this->retryWhenCallback);
}
/**
* Parse multi-part form data.
*
* @param array $data
* @return array|array[]
*/
protected function parseMultipartBodyFormat(array $data)
{
return collect($data)->map(function ($value, $key) {
return is_array($value) ? $value : ['name' => $key, 'contents' => $value];
})->values()->all();
}
/**
* Send an asynchronous request to the given URL.
*
* @param string $method
* @param string $url
* @param array $options
* @return \GuzzleHttp\Promise\PromiseInterface
*/
protected function makePromise(string $method, string $url, array $options = [])
{
return $this->promise = $this->sendRequest($method, $url, $options)
->then(function (MessageInterface $message) {
return tap(new Response($message), function ($response) {
$this->populateResponse($response);
$this->dispatchResponseReceivedEvent($response);
});
})
->otherwise(function (TransferException $e) {
return $e instanceof RequestException ? $this->populateResponse(new Response($e->getResponse())) : $e;
});
}
/**
* Send a request either synchronously or asynchronously.
*
* @param string $method
* @param string $url
* @param array $options
* @return \Psr\Http\Message\MessageInterface|\GuzzleHttp\Promise\PromiseInterface
*
* @throws \Exception
*/
protected function sendRequest(string $method, string $url, array $options = [])
{
$clientMethod = $this->async ? 'requestAsync' : 'request';
$laravelData = $this->parseRequestData($method, $url, $options);
return $this->buildClient()->$clientMethod($method, $url, $this->mergeOptions([
'laravel_data' => $laravelData,
'on_stats' => function ($transferStats) {
$this->transferStats = $transferStats;
},
], $options));
}
/**
* Get the request data as an array so that we can attach it to the request for convenient assertions.
*
* @param string $method
* @param string $url
* @param array $options
* @return array
*/
protected function parseRequestData($method, $url, array $options)
{
$laravelData = $options[$this->bodyFormat] ?? $options['query'] ?? [];
$urlString = Str::of($url);
if (empty($laravelData) && $method === 'GET' && $urlString->contains('?')) {
$laravelData = (string) $urlString->after('?');
}
if (is_string($laravelData)) {
parse_str($laravelData, $parsedData);
$laravelData = is_array($parsedData) ? $parsedData : [];
}
return $laravelData;
}
/**
* Populate the given response with additional data.
*
* @param \Illuminate\Http\Client\Response $response
* @return \Illuminate\Http\Client\Response
*/
protected function populateResponse(Response $response)
{
$response->cookies = $this->cookies;
$response->transferStats = $this->transferStats;
return $response;
}
/**
* Build the Guzzle client.
*
* @return \GuzzleHttp\Client
*/
public function buildClient()
{
return $this->requestsReusableClient()
? $this->getReusableClient()
: $this->createClient($this->buildHandlerStack());
}
/**
* Determine if a reusable client is required.
*
* @return bool
*/
protected function requestsReusableClient()
{
return ! is_null($this->client) || $this->async;
}
/**
* Retrieve a reusable Guzzle client.
*
* @return \GuzzleHttp\Client
*/
protected function getReusableClient()
{
return $this->client = $this->client ?: $this->createClient($this->buildHandlerStack());
}
/**
* Create new Guzzle client.
*
* @param \GuzzleHttp\HandlerStack $handlerStack
* @return \GuzzleHttp\Client
*/
public function createClient($handlerStack)
{
return new Client([
'handler' => $handlerStack,
'cookies' => true,
]);
}
/**
* Build the Guzzle client handler stack.
*
* @return \GuzzleHttp\HandlerStack
*/
public function buildHandlerStack()
{
return $this->pushHandlers(HandlerStack::create());
}
/**
* Add the necessary handlers to the given handler stack.
*
* @param \GuzzleHttp\HandlerStack $handlerStack
* @return \GuzzleHttp\HandlerStack
*/
public function pushHandlers($handlerStack)
{
return tap($handlerStack, function ($stack) {
$stack->push($this->buildBeforeSendingHandler());
$stack->push($this->buildRecorderHandler());
$stack->push($this->buildStubHandler());
$this->middleware->each(function ($middleware) use ($stack) {
$stack->push($middleware);
});
});
}
/**
* Build the before sending handler.
*
* @return \Closure
*/
public function buildBeforeSendingHandler()
{
return function ($handler) {
return function ($request, $options) use ($handler) {
return $handler($this->runBeforeSendingCallbacks($request, $options), $options);
};
};
}
/**
* Build the recorder handler.
*
* @return \Closure
*/
public function buildRecorderHandler()
{
return function ($handler) {
return function ($request, $options) use ($handler) {
$promise = $handler($request, $options);
return $promise->then(function ($response) use ($request, $options) {
optional($this->factory)->recordRequestResponsePair(
(new Request($request))->withData($options['laravel_data']),
new Response($response)
);
return $response;
});
};
};
}
/**
* Build the stub handler.
*
* @return \Closure
*/
public function buildStubHandler()
{
return function ($handler) {
return function ($request, $options) use ($handler) {
$response = ($this->stubCallbacks ?? collect())
->map
->__invoke((new Request($request))->withData($options['laravel_data']), $options)
->filter()
->first();
if (is_null($response)) {
return $handler($request, $options);
}
$response = is_array($response) ? Factory::response($response) : $response;
$sink = $options['sink'] ?? null;
if ($sink) {
$response->then($this->sinkStubHandler($sink));
}
return $response;
};
};
}
/**
* Get the sink stub handler callback.
*
* @param string $sink
* @return \Closure
*/
protected function sinkStubHandler($sink)
{
return function ($response) use ($sink) {
$body = $response->getBody()->getContents();
if (is_string($sink)) {
file_put_contents($sink, $body);
return;
}
fwrite($sink, $body);
rewind($sink);
};
}
/**
* Execute the "before sending" callbacks.
*
* @param \GuzzleHttp\Psr7\RequestInterface $request
* @param array $options
* @return \GuzzleHttp\Psr7\RequestInterface
*/
public function runBeforeSendingCallbacks($request, array $options)
{
return tap($request, function (&$request) use ($options) {
$this->beforeSendingCallbacks->each(function ($callback) use (&$request, $options) {
$callbackResult = call_user_func(
$callback, (new Request($request))->withData($options['laravel_data']), $options, $this
);
if ($callbackResult instanceof RequestInterface) {
$request = $callbackResult;
} elseif ($callbackResult instanceof Request) {
$request = $callbackResult->toPsrRequest();
}
});
});
}
/**
* Replace the given options with the current request options.
*
* @param array $options
* @return array
*/
public function mergeOptions(...$options)
{
return array_replace_recursive(
array_merge_recursive($this->options, Arr::only($options, $this->mergableOptions)),
...$options
);
}
/**
* Register a stub callable that will intercept requests and be able to return stub responses.
*
* @param callable $callback
* @return $this
*/
public function stub($callback)
{
$this->stubCallbacks = collect($callback);
return $this;
}
/**
* Toggle asynchronicity in requests.
*
* @param bool $async
* @return $this
*/
public function async(bool $async = true)
{
$this->async = $async;
return $this;
}
/**
* Retrieve the pending request promise.
*
* @return \GuzzleHttp\Promise\PromiseInterface|null
*/
public function getPromise()
{
return $this->promise;
}
/**
* Dispatch the RequestSending event if a dispatcher is available.
*
* @return void
*/
protected function dispatchRequestSendingEvent()
{
if ($dispatcher = optional($this->factory)->getDispatcher()) {
$dispatcher->dispatch(new RequestSending($this->request));
}
}
/**
* Dispatch the ResponseReceived event if a dispatcher is available.
*
* @param \Illuminate\Http\Client\Response $response
* @return void
*/
protected function dispatchResponseReceivedEvent(Response $response)
{
if (! ($dispatcher = optional($this->factory)->getDispatcher()) ||
! $this->request) {
return;
}
$dispatcher->dispatch(new ResponseReceived($this->request, $response));
}
/**
* Dispatch the ConnectionFailed event if a dispatcher is available.
*
* @return void
*/
protected function dispatchConnectionFailedEvent()
{
if ($dispatcher = optional($this->factory)->getDispatcher()) {
$dispatcher->dispatch(new ConnectionFailed($this->request));
}
}
/**
* Set the client instance.
*
* @param \GuzzleHttp\Client $client
* @return $this
*/
public function setClient(Client $client)
{
$this->client = $client;
return $this;
}
/**
* Create a new client instance using the given handler.
*
* @param callable $handler
* @return $this
*/
public function setHandler($handler)
{
$this->client = $this->createClient(
$this->pushHandlers(HandlerStack::create($handler))
);
return $this;
}
/**
* Get the pending request options.
*
* @return array
*/
public function getOptions()
{
return $this->options;
}
}