-
Notifications
You must be signed in to change notification settings - Fork 11.1k
/
Copy pathFactory.php
429 lines (380 loc) · 13 KB
/
Factory.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
<?php
namespace Illuminate\Http\Client;
use Closure;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Response as Psr7Response;
use GuzzleHttp\TransferStats;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use PHPUnit\Framework\Assert as PHPUnit;
/**
* @method \Illuminate\Http\Client\PendingRequest accept(string $contentType)
* @method \Illuminate\Http\Client\PendingRequest acceptJson()
* @method \Illuminate\Http\Client\PendingRequest asForm()
* @method \Illuminate\Http\Client\PendingRequest asJson()
* @method \Illuminate\Http\Client\PendingRequest asMultipart()
* @method \Illuminate\Http\Client\PendingRequest async()
* @method \Illuminate\Http\Client\PendingRequest attach(string|array $name, string|resource $contents = '', string|null $filename = null, array $headers = [])
* @method \Illuminate\Http\Client\PendingRequest baseUrl(string $url)
* @method \Illuminate\Http\Client\PendingRequest beforeSending(callable $callback)
* @method \Illuminate\Http\Client\PendingRequest bodyFormat(string $format)
* @method \Illuminate\Http\Client\PendingRequest connectTimeout(int $seconds)
* @method \Illuminate\Http\Client\PendingRequest contentType(string $contentType)
* @method \Illuminate\Http\Client\PendingRequest dd()
* @method \Illuminate\Http\Client\PendingRequest dump()
* @method \Illuminate\Http\Client\PendingRequest maxRedirects(int $max)
* @method \Illuminate\Http\Client\PendingRequest retry(int $times, int $sleepMilliseconds = 0, ?callable $when = null, bool $throw = true)
* @method \Illuminate\Http\Client\PendingRequest sink(string|resource $to)
* @method \Illuminate\Http\Client\PendingRequest stub(callable $callback)
* @method \Illuminate\Http\Client\PendingRequest timeout(int $seconds)
* @method \Illuminate\Http\Client\PendingRequest withBasicAuth(string $username, string $password)
* @method \Illuminate\Http\Client\PendingRequest withBody(resource|string $content, string $contentType)
* @method \Illuminate\Http\Client\PendingRequest withCookies(array $cookies, string $domain)
* @method \Illuminate\Http\Client\PendingRequest withDigestAuth(string $username, string $password)
* @method \Illuminate\Http\Client\PendingRequest withHeaders(array $headers)
* @method \Illuminate\Http\Client\PendingRequest withMiddleware(callable $middleware)
* @method \Illuminate\Http\Client\PendingRequest withOptions(array $options)
* @method \Illuminate\Http\Client\PendingRequest withToken(string $token, string $type = 'Bearer')
* @method \Illuminate\Http\Client\PendingRequest withUserAgent(string $userAgent)
* @method \Illuminate\Http\Client\PendingRequest withoutRedirecting()
* @method \Illuminate\Http\Client\PendingRequest withoutVerifying()
* @method \Illuminate\Http\Client\PendingRequest throw(callable $callback = null)
* @method \Illuminate\Http\Client\PendingRequest throwIf($condition)
* @method \Illuminate\Http\Client\PendingRequest throwUnless($condition)
* @method array pool(callable $callback)
* @method \Illuminate\Http\Client\Response delete(string $url, array $data = [])
* @method \Illuminate\Http\Client\Response get(string $url, array|string|null $query = null)
* @method \Illuminate\Http\Client\Response head(string $url, array|string|null $query = null)
* @method \Illuminate\Http\Client\Response patch(string $url, array $data = [])
* @method \Illuminate\Http\Client\Response post(string $url, array $data = [])
* @method \Illuminate\Http\Client\Response put(string $url, array $data = [])
* @method \Illuminate\Http\Client\Response send(string $method, string $url, array $options = [])
*
* @see \Illuminate\Http\Client\PendingRequest
*/
class Factory
{
use Macroable {
__call as macroCall;
}
/**
* The event dispatcher implementation.
*
* @var \Illuminate\Contracts\Events\Dispatcher|null
*/
protected $dispatcher;
/**
* The stub callables that will handle requests.
*
* @var \Illuminate\Support\Collection
*/
protected $stubCallbacks;
/**
* Indicates if the factory is recording requests and responses.
*
* @var bool
*/
protected $recording = false;
/**
* The recorded response array.
*
* @var array
*/
protected $recorded = [];
/**
* All created response sequences.
*
* @var array
*/
protected $responseSequences = [];
/**
* Indicates that an exception should be thrown if any request is not faked.
*
* @var bool
*/
protected $preventStrayRequests = false;
/**
* Create a new factory instance.
*
* @param \Illuminate\Contracts\Events\Dispatcher|null $dispatcher
* @return void
*/
public function __construct(Dispatcher $dispatcher = null)
{
$this->dispatcher = $dispatcher;
$this->stubCallbacks = collect();
}
/**
* Create a new response instance for use during stubbing.
*
* @param array|string|null $body
* @param int $status
* @param array $headers
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public static function response($body = null, $status = 200, $headers = [])
{
if (is_array($body)) {
$body = json_encode($body);
$headers['Content-Type'] = 'application/json';
}
$response = new Psr7Response($status, $headers, $body);
return class_exists(\GuzzleHttp\Promise\Create::class)
? \GuzzleHttp\Promise\Create::promiseFor($response)
: \GuzzleHttp\Promise\promise_for($response);
}
/**
* Get an invokable object that returns a sequence of responses in order for use during stubbing.
*
* @param array $responses
* @return \Illuminate\Http\Client\ResponseSequence
*/
public function sequence(array $responses = [])
{
return $this->responseSequences[] = new ResponseSequence($responses);
}
/**
* Register a stub callable that will intercept requests and be able to return stub responses.
*
* @param callable|array|null $callback
* @return $this
*/
public function fake($callback = null)
{
$this->record();
$this->recorded = [];
if (is_null($callback)) {
$callback = function () {
return static::response();
};
}
if (is_array($callback)) {
foreach ($callback as $url => $callable) {
$this->stubUrl($url, $callable);
}
return $this;
}
$this->stubCallbacks = $this->stubCallbacks->merge(collect([
function ($request, $options) use ($callback) {
$response = $callback instanceof Closure
? $callback($request, $options)
: $callback;
if ($response instanceof PromiseInterface) {
$options['on_stats'](new TransferStats(
$request->toPsrRequest(),
$response->wait(),
));
}
return $response;
},
]));
return $this;
}
/**
* Register a response sequence for the given URL pattern.
*
* @param string $url
* @return \Illuminate\Http\Client\ResponseSequence
*/
public function fakeSequence($url = '*')
{
return tap($this->sequence(), function ($sequence) use ($url) {
$this->fake([$url => $sequence]);
});
}
/**
* Stub the given URL using the given callback.
*
* @param string $url
* @param \Illuminate\Http\Client\Response|\GuzzleHttp\Promise\PromiseInterface|callable $callback
* @return $this
*/
public function stubUrl($url, $callback)
{
return $this->fake(function ($request, $options) use ($url, $callback) {
if (! Str::is(Str::start($url, '*'), $request->url())) {
return;
}
return $callback instanceof Closure || $callback instanceof ResponseSequence
? $callback($request, $options)
: $callback;
});
}
/**
* Indicate that an exception should be thrown if any request is not faked.
*
* @param bool $prevent
* @return $this
*/
public function preventStrayRequests($prevent = true)
{
$this->preventStrayRequests = $prevent;
return $this;
}
/**
* Indicate that an exception should not be thrown if any request is not faked.
*
* @return $this
*/
public function allowStrayRequests()
{
return $this->preventStrayRequests(false);
}
/**
* Begin recording request / response pairs.
*
* @return $this
*/
protected function record()
{
$this->recording = true;
return $this;
}
/**
* Record a request response pair.
*
* @param \Illuminate\Http\Client\Request $request
* @param \Illuminate\Http\Client\Response $response
* @return void
*/
public function recordRequestResponsePair($request, $response)
{
if ($this->recording) {
$this->recorded[] = [$request, $response];
}
}
/**
* Assert that a request / response pair was recorded matching a given truth test.
*
* @param callable $callback
* @return void
*/
public function assertSent($callback)
{
PHPUnit::assertTrue(
$this->recorded($callback)->count() > 0,
'An expected request was not recorded.'
);
}
/**
* Assert that the given request was sent in the given order.
*
* @param array $callbacks
* @return void
*/
public function assertSentInOrder($callbacks)
{
$this->assertSentCount(count($callbacks));
foreach ($callbacks as $index => $url) {
$callback = is_callable($url) ? $url : function ($request) use ($url) {
return $request->url() == $url;
};
PHPUnit::assertTrue($callback(
$this->recorded[$index][0],
$this->recorded[$index][1]
), 'An expected request (#'.($index + 1).') was not recorded.');
}
}
/**
* Assert that a request / response pair was not recorded matching a given truth test.
*
* @param callable $callback
* @return void
*/
public function assertNotSent($callback)
{
PHPUnit::assertFalse(
$this->recorded($callback)->count() > 0,
'Unexpected request was recorded.'
);
}
/**
* Assert that no request / response pair was recorded.
*
* @return void
*/
public function assertNothingSent()
{
PHPUnit::assertEmpty(
$this->recorded,
'Requests were recorded.'
);
}
/**
* Assert how many requests have been recorded.
*
* @param int $count
* @return void
*/
public function assertSentCount($count)
{
PHPUnit::assertCount($count, $this->recorded);
}
/**
* Assert that every created response sequence is empty.
*
* @return void
*/
public function assertSequencesAreEmpty()
{
foreach ($this->responseSequences as $responseSequence) {
PHPUnit::assertTrue(
$responseSequence->isEmpty(),
'Not all response sequences are empty.'
);
}
}
/**
* Get a collection of the request / response pairs matching the given truth test.
*
* @param callable $callback
* @return \Illuminate\Support\Collection
*/
public function recorded($callback = null)
{
if (empty($this->recorded)) {
return collect();
}
$callback = $callback ?: function () {
return true;
};
return collect($this->recorded)->filter(function ($pair) use ($callback) {
return $callback($pair[0], $pair[1]);
});
}
/**
* Create a new pending request instance for this factory.
*
* @return \Illuminate\Http\Client\PendingRequest
*/
protected function newPendingRequest()
{
return new PendingRequest($this);
}
/**
* Get the current event dispatcher implementation.
*
* @return \Illuminate\Contracts\Events\Dispatcher|null
*/
public function getDispatcher()
{
return $this->dispatcher;
}
/**
* Execute a method against a new pending request instance.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
if (static::hasMacro($method)) {
return $this->macroCall($method, $parameters);
}
return tap($this->newPendingRequest(), function ($request) {
$request->stub($this->stubCallbacks)->preventStrayRequests($this->preventStrayRequests);
})->{$method}(...$parameters);
}
}