Skip to content

[2.x] Feat: Add strict model serialization #630

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/Exceptions/StrictPropertiesException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Inertia\Exceptions;

class StrictPropertiesException extends \Exception
{
public static function for(string $key): self
{
return new static("Prop \"{$key}\" is shared without serialization rules.");
}
}
34 changes: 32 additions & 2 deletions src/Response.php
Original file line number Diff line number Diff line change
@@ -6,6 +6,7 @@
use GuzzleHttp\Promise\PromiseInterface;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
@@ -15,6 +16,7 @@
use Illuminate\Support\Facades\Response as ResponseFactory;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use Inertia\Exceptions\StrictPropertiesException;
use Inertia\Support\Header;

class Response implements Responsable
@@ -31,15 +33,24 @@ class Response implements Responsable

protected $viewData = [];

protected $strictModels = false;


/**
* @param array|Arrayable $props
*/
public function __construct(string $component, array $props, string $rootView = 'app', string $version = '')
{
public function __construct(
string $component,
array $props,
string $rootView = 'app',
string $version = '',
bool $strictModels = false
) {
$this->component = $component;
$this->props = $props instanceof Arrayable ? $props->toArray() : $props;
$this->rootView = $rootView;
$this->version = $version;
$this->strictModels = $strictModels;
}

/**
@@ -142,6 +153,10 @@ public function resolveArrayableProperties(array $props, Request $request, bool
{
foreach ($props as $key => $value) {
if ($value instanceof Arrayable) {
if ($this->strictModels) {
$this->checkStrictModel($key, $value);
}

$value = $value->toArray();
}

@@ -225,6 +240,10 @@ public function resolvePropertyInstances(array $props, Request $request): array
$value = $value->wait();
}

if ($this->strictModels) {
$this->checkStrictModel($key, $value);
}

if ($value instanceof ResourceResponse || $value instanceof JsonResource) {
$value = $value->toResponse($request)->getData(true);
}
@@ -238,4 +257,15 @@ public function resolvePropertyInstances(array $props, Request $request): array

return $props;
}

protected function checkStrictModel($key, $prop): void
{
if (! ($prop instanceof Model)) {
return;
}

if (empty($prop->getVisible()) && empty($prop->getHidden())) {
throw StrictPropertiesException::for($key);
}
}
}
10 changes: 9 additions & 1 deletion src/ResponseFactory.php
Original file line number Diff line number Diff line change
@@ -27,6 +27,8 @@ class ResponseFactory
/** @var Closure|string|null */
protected $version;

protected $strictModels = false;

public function setRootView(string $name): void
{
$this->rootView = $name;
@@ -108,7 +110,8 @@ public function render(string $component, $props = []): Response
$component,
array_merge($this->sharedProps, $props),
$this->rootView,
$this->getVersion()
$this->getVersion(),
$this->strictModels,
);
}

@@ -123,4 +126,9 @@ public function location($url): SymfonyResponse

return $url instanceof SymfonyRedirect ? $url : Redirect::away($url);
}

public function strictModels(bool $enabled = true): void
{
$this->strictModels = $enabled;
}
}
119 changes: 119 additions & 0 deletions tests/ResponseFactoryTest.php
Original file line number Diff line number Diff line change
@@ -3,15 +3,18 @@
namespace Inertia\Tests;

use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Foundation\Auth\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request as HttpRequest;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Response;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\Session\NullSessionHandler;
use Illuminate\Session\Store;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Route;
use Inertia\AlwaysProp;
use Inertia\Exceptions\StrictPropertiesException;
use Inertia\Inertia;
use Inertia\LazyProp;
use Inertia\ResponseFactory;
@@ -196,4 +199,120 @@ public function toArray()
],
]);
}

public function test_strict_models_mode_checks_if_models_have_serialization_rules()
{
$this->expectException(StrictPropertiesException::class);
$this->expectExceptionMessage('Prop "user" is shared without serialization rules.');

Route::middleware([StartSession::class, ExampleMiddleware::class])->get('/', function () {
Inertia::strictModels();

return Inertia::render('User/Edit', [
'user' => new class(['name' => 'John', 'email' => 'john@doe.com']) extends User {
protected $fillable = [
'name',
];
},
]);
});

$this->withoutExceptionHandling()->get('/', ['X-Inertia' => 'true']);
}

public function test_strict_models_mode_allows_models_with_hidden_serialization_rules()
{
Route::middleware([StartSession::class, ExampleMiddleware::class])->get('/', function () {
Inertia::strictModels();

return Inertia::render('User/Edit', [
'user' => new class(['name' => 'John', 'email' => 'john@doe.com']) extends User {
protected $fillable = [
'name',
'email',
];

protected $hidden = ['email'];
},
]);
});

$response = $this->withoutExceptionHandling()->get('/', ['X-Inertia' => 'true']);
$response->assertSuccessful();
$response->assertJson([
'component' => 'User/Edit',
'props' => [
'user' => [
'name' => 'John',
],
],
]);
}

public function test_strict_models_mode_allows_models_with_visible_serialization_rules()
{
Route::middleware([StartSession::class, ExampleMiddleware::class])->get('/', function () {
Inertia::strictModels();

return Inertia::render('User/Edit', [
'user' => new class(['name' => 'John', 'email' => 'john@doe.com']) extends User {
protected $fillable = [
'name',
'email',
];

protected $visible = ['name'];
},
]);
});

$response = $this->withoutExceptionHandling()->get('/', ['X-Inertia' => 'true']);
$response->assertSuccessful();
$response->assertJson([
'component' => 'User/Edit',
'props' => [
'user' => [
'name' => 'John',
],
],
]);
}

public function test_strict_models_allows_wrapping_in_json_resources()
{
Route::middleware([StartSession::class, ExampleMiddleware::class])->get('/', function () {
Inertia::strictModels();

$user = new class(['name' => 'John', 'email' => 'john@doe.com']) extends User {
protected $fillable = [
'name',
'email',
];
};

return Inertia::render('User/Edit', [
'user' => new class($user) extends JsonResource {
public static $wrap = null;

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

$response = $this->withoutExceptionHandling()->get('/', ['X-Inertia' => 'true']);
$response->assertSuccessful();
$response->assertJson([
'component' => 'User/Edit',
'props' => [
'user' => [
'name' => 'John',
],
],
]);
}
}
Loading
Oops, something went wrong.