Skip to content

Commit

Permalink
[8.x] Adds a collect method to the HTTP Client response. (#36331)
Browse files Browse the repository at this point in the history
* Adds a `collect` method to the HTTP client response.

* Formatting change

* Allows passing a key to the `collect` method that will return a subset of the json response before wrapping it in the collection.

* Update Response.php

* Update Response.php

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
lukeraymonddowning and taylorotwell authored Feb 21, 2021
1 parent 054c391 commit bb9078a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/Illuminate/Http/Client/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Illuminate\Http\Client;

use ArrayAccess;
use Illuminate\Support\Collection;
use Illuminate\Support\Traits\Macroable;
use LogicException;

Expand Down Expand Up @@ -77,6 +78,17 @@ public function object()
return json_decode($this->body(), false);
}

/**
* Get the JSON decoded body of the response as a collection.
*
* @param string|null $key
* @return \Illuminate\Support\Collection
*/
public function collect($key = null)
{
return Collection::make($this->json($key));
}

/**
* Get a header from the response.
*
Expand Down
16 changes: 16 additions & 0 deletions tests/Http/HttpClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Illuminate\Http\Client\Request;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use OutOfBoundsException;
use PHPUnit\Framework\TestCase;
Expand Down Expand Up @@ -54,6 +55,21 @@ public function testResponseBodyCasting()
$this->assertSame('bar', $response->object()->result->foo);
}

public function testResponseCanBeReturnedAsCollection()
{
$this->factory->fake([
'*' => ['result' => ['foo' => 'bar']],
]);

$response = $this->factory->get('http://foo.com/api');

$this->assertInstanceOf(Collection::class, $response->collect());
$this->assertEquals(collect(['result' => ['foo' => 'bar']]), $response->collect());
$this->assertEquals(collect(['foo' => 'bar']), $response->collect('result'));
$this->assertEquals(collect(['bar']), $response->collect('result.foo'));
$this->assertEquals(collect(), $response->collect('missing_key'));
}

public function testUrlsCanBeStubbedByPath()
{
$this->factory->fake([
Expand Down

0 comments on commit bb9078a

Please sign in to comment.