Skip to content

Commit

Permalink
[8.x] Enable to modify HTTP Client request headers when using beforeS…
Browse files Browse the repository at this point in the history
…ending() callback (#42244)

* Fix return docblock definition

* Adding reference on $request parameter and retrieve the latest value from the given callback

* Create unit test to assert if http factory can add authorization header using before sending callback
  • Loading branch information
ianriizky authored May 3, 2022
1 parent d85c341 commit 6e5e599
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/Illuminate/Http/Client/PendingRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
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
Expand Down Expand Up @@ -984,15 +985,21 @@ protected function sinkStubHandler($sink)
*
* @param \GuzzleHttp\Psr7\RequestInterface $request
* @param array $options
* @return \Closure
* @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) {
call_user_func(
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();
}
});
});
}
Expand Down
22 changes: 22 additions & 0 deletions tests/Http/HttpClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1080,4 +1080,26 @@ public function testRequestIsMacroable()

$this->factory->get('https://example.com');
}

public function testItCanAddAuthorizationHeaderIntoRequestUsingBeforeSendingCallback()
{
$this->factory->fake();

$this->factory->beforeSending(function (Request $request) {
$requestLine = sprintf(
'%s %s HTTP/%s',
$request->toPsrRequest()->getMethod(),
$request->toPsrRequest()->getUri()->withScheme('')->withHost(''),
$request->toPsrRequest()->getProtocolVersion()
);

return $request->toPsrRequest()->withHeader('Authorization', 'Bearer '.$requestLine);
})->get('http://foo.com/json');

$this->factory->assertSent(function (Request $request) {
return
$request->url() === 'http://foo.com/json' &&
$request->hasHeader('Authorization', 'Bearer GET /json HTTP/1.1');
});
}
}

0 comments on commit 6e5e599

Please sign in to comment.