Skip to content

Commit

Permalink
Merge pull request #102 from fourstacks/recursive-arrayable-props
Browse files Browse the repository at this point in the history
Add Arrayable support for nested props
  • Loading branch information
reinink authored Feb 28, 2020
2 parents fbd2afc + 0fd7b01 commit ef61873
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ public function toResponse($request)
if ($prop instanceof Responsable) {
$prop = $prop->toResponse($request)->getData();
}

if ($prop instanceof Arrayable) {
$prop = $prop->toArray();
}
});

$page = [
Expand Down
34 changes: 34 additions & 0 deletions tests/ResponseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Inertia\Tests;

use Illuminate\Contracts\Support\Arrayable;
use Inertia\Response;
use Illuminate\View\View;
use Illuminate\Http\Request;
Expand Down Expand Up @@ -126,4 +127,37 @@ public function test_lazy_resource_response()
$this->assertSame('/users?page=1', $page->url);
$this->assertSame('123', $page->version);
}

public function test_arrayable_prop_response()
{
$request = Request::create('/user/123', 'GET');
$request->headers->add(['X-Inertia' => 'true']);

$user = (object) ['name' => 'Jonathan'];

$resource = new class($user) implements Arrayable {

public $user;

public function __construct($user)
{
$this->user = $user;
}

public function toArray()
{
return ['name' => $this->user->name];
}
};

$response = new Response('User/Edit', ['user' => $resource], 'app', '123');
$response = $response->toResponse($request);
$page = $response->getData();

$this->assertInstanceOf(JsonResponse::class, $response);
$this->assertSame('User/Edit', $page->component);
$this->assertSame('Jonathan', $page->props->user->name);
$this->assertSame('/user/123', $page->url);
$this->assertSame('123', $page->version);
}
}

0 comments on commit ef61873

Please sign in to comment.