Skip to content

Commit

Permalink
Implement ArrayAccess on TestResponse (#30817)
Browse files Browse the repository at this point in the history
When building / testing and JSON API, I like to sometimes interact with the raw JSON payload returned in the response. Normally you would have to access this via $response->original['foo']; however, with this change I implement ArrayAccess on both JsonResponse and TestResponse in order to be able to proxy directly into the response JSON without going through the original property.
  • Loading branch information
taylorotwell authored Dec 11, 2019
1 parent d8122e6 commit f5c3c60
Showing 1 changed file with 48 additions and 1 deletion.
49 changes: 48 additions & 1 deletion src/Illuminate/Foundation/Testing/TestResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Foundation\Testing;

use ArrayAccess;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Model;
Expand All @@ -12,12 +13,13 @@
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Support\Traits\Tappable;
use LogicException;
use Symfony\Component\HttpFoundation\StreamedResponse;

/**
* @mixin \Illuminate\Http\Response
*/
class TestResponse
class TestResponse implements ArrayAccess
{
use Tappable, Macroable {
__call as macroCall;
Expand Down Expand Up @@ -1210,6 +1212,51 @@ public function __isset($key)
return isset($this->baseResponse->{$key});
}

/**
* Determine if the given offset exists.
*
* @param string $offset
* @return bool
*/
public function offsetExists($offset)
{
return isset($this->json()[$offset]);
}

/**
* Get the value for a given offset.
*
* @param string $offset
* @return mixed
*/
public function offsetGet($offset)
{
return $this->json()[$offset];
}

/**
* Set the value at the given offset.
*
* @param string $offset
* @param mixed $value
* @return void
*/
public function offsetSet($offset, $value)
{
throw new LogicException('Response data may not be mutated using array access.');
}

/**
* Unset the value at the given offset.
*
* @param string $offset
* @return void
*/
public function offsetUnset($offset)
{
throw new LogicException('Response data may not be mutated using array access.');
}

/**
* Handle dynamic calls into macros or pass missing methods to the base response.
*
Expand Down

0 comments on commit f5c3c60

Please sign in to comment.