Skip to content

Commit 2edd9a9

Browse files
authored
[11.x] Add ability to transform Http\Client\Response into Fluent (#53771)
* Add ability to transform a response into a fluent instance * Add tests
1 parent ea35f41 commit 2edd9a9

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/Illuminate/Http/Client/Response.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use ArrayAccess;
66
use GuzzleHttp\Psr7\StreamWrapper;
77
use Illuminate\Support\Collection;
8+
use Illuminate\Support\Fluent;
89
use Illuminate\Support\Traits\Macroable;
910
use LogicException;
1011
use Stringable;
@@ -108,6 +109,17 @@ public function collect($key = null)
108109
return new Collection($this->json($key));
109110
}
110111

112+
/**
113+
* Get the JSON decoded body of the response as a fluent object.
114+
*
115+
* @param string|null $key
116+
* @return \Illuminate\Support\Fluent
117+
*/
118+
public function fluent($key = null)
119+
{
120+
return new Fluent((array) $this->json($key));
121+
}
122+
111123
/**
112124
* Get the body of the response as a PHP resource.
113125
*

tests/Http/HttpClientTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,21 @@ public function testResponseCanBeReturnedAsCollection()
402402
$this->assertEquals(collect(), $response->collect('missing_key'));
403403
}
404404

405+
public function testResponseCanBeReturnedAsFluent()
406+
{
407+
$this->factory->fake([
408+
'*' => ['result' => ['foo' => 'bar']],
409+
]);
410+
411+
$response = $this->factory->get('http://foo.com/api');
412+
413+
$this->assertInstanceOf(Fluent::class, $response->fluent());
414+
$this->assertEquals(fluent(['result' => ['foo' => 'bar']]), $response->fluent());
415+
$this->assertEquals(fluent(['foo' => 'bar']), $response->fluent('result'));
416+
$this->assertEquals(fluent(['bar']), $response->fluent('result.foo'));
417+
$this->assertEquals(fluent([]), $response->fluent('missing_key'));
418+
}
419+
405420
public function testSendRequestBodyAsJsonByDefault()
406421
{
407422
$body = '{"test":"phpunit"}';

0 commit comments

Comments
 (0)