Skip to content

Commit 30552f8

Browse files
committed
Add on request callback hook to the http client
1 parent f30422f commit 30552f8

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

src/Illuminate/Http/Client/Factory.php

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@ class Factory
2828
*/
2929
protected $dispatcher;
3030

31+
/**
32+
* The callbacks that should execute before every request is sent.
33+
*
34+
* @var array
35+
*/
36+
protected $beforeSendingCallbacks = [];
37+
3138
/**
3239
* The stub callables that will handle requests.
3340
*
@@ -76,6 +83,19 @@ public function __construct(Dispatcher $dispatcher = null)
7683
$this->stubCallbacks = collect();
7784
}
7885

86+
/**
87+
* Add a new "before sending" callback to every request.
88+
*
89+
* @param callable $callback
90+
* @return $this
91+
*/
92+
public function beforeSending($callback)
93+
{
94+
$this->beforeSendingCallbacks[] = $callback;
95+
96+
return $this;
97+
}
98+
7999
/**
80100
* Create a new response instance for use during stubbing.
81101
*
@@ -353,7 +373,11 @@ public function recorded($callback = null)
353373
*/
354374
protected function newPendingRequest()
355375
{
356-
return new PendingRequest($this);
376+
return tap(new PendingRequest($this), function ($request) {
377+
foreach ($this->beforeSendingCallbacks as $callback) {
378+
$request->beforeSending($callback);
379+
}
380+
});
357381
}
358382

359383
/**

tests/Http/HttpClientTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2316,4 +2316,23 @@ public function testTheTransferStatsAreCustomizableOnFake(): void
23162316

23172317
$this->assertTrue($onStatsFunctionCalled);
23182318
}
2319+
2320+
public function testItCanMakeGlobalChangesToNewPendingRequests()
2321+
{
2322+
$request = null;
2323+
$this->factory->beforeSending(function (Request $request, array $options, PendingRequest $pending) {
2324+
return $request->toPsrRequest()->withHeader('User-Agent', 'Laravel Framework/1.0');
2325+
});
2326+
$this->factory->fake(function ($r) use (&$request) {
2327+
$request = $r;
2328+
2329+
return $this->factory::response('expected content');
2330+
});
2331+
2332+
$response = $this->factory->post('http://vapor.laravel.com');
2333+
2334+
$this->assertSame('expected content', $response->body());
2335+
$this->assertNotNull($request);
2336+
$this->assertSame(['Laravel Framework/1.0'], $request->header('User-Agent'));
2337+
}
23192338
}

0 commit comments

Comments
 (0)