Skip to content
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

Use container to call Data::authorize() to allow for dependencies #910

Merged
merged 2 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion src/DataPipes/AuthorizedDataPipe.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public function handle(
protected function ensureRequestIsAuthorized(string $class): void
{
/** @psalm-suppress UndefinedMethod */
if (method_exists($class, 'authorize') && $class::authorize() === false) {
if (method_exists($class, 'authorize') && app()->call([$class, 'authorize']) === false) {
throw new AuthorizationException();
}
}
Expand Down
36 changes: 36 additions & 0 deletions tests/RequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,3 +143,39 @@ public static function fromRequest(Request $request)
->assertJson(['name' => 'Rick Astley']);
}
);

it('can build authorize parameters from the container', function (): void {
class SomeDependency
{
public function __construct(public string $street)
{
}
}

app()->bind(SomeDependency::class, fn () => new SomeDependency('Sesame'));
class AuthorizeFromContainerRequest extends Data
{
public static string $street;

public function __construct(public string $name)
{
}

public static function authorize(SomeDependency $dependency): bool
{
self::$street = $dependency->street;

return $dependency->street === 'Sesame';
}
}

Route::post('/route-with-authorization-dependencies', function (\AuthorizeFromContainerRequest $data) {
return ['name' => $data->name, 'street' => \AuthorizeFromContainerRequest::$street];
});

postJson('/route-with-authorization-dependencies', [
'name' => 'Rick Astley',
])
->assertOk()
->assertJson(['name' => 'Rick Astley', 'street' => 'Sesame']);
});