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

[10.x] Add "substituteImplicitBindingsUsing" method to router #49200

Merged
merged 4 commits into from
Nov 30, 2023
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
27 changes: 26 additions & 1 deletion src/Illuminate/Routing/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,13 @@ class Router implements BindingRegistrar, RegistrarContract
*/
protected $groupStack = [];

/**
* The registered custom implicit binding callback.
*
* @var array
*/
protected $implicitBindingCallback;

/**
* All of the verbs supported by the router.
*
Expand Down Expand Up @@ -949,7 +956,25 @@ public function substituteBindings($route)
*/
public function substituteImplicitBindings($route)
{
ImplicitRouteBinding::resolveForRoute($this->container, $route);
$default = fn () => ImplicitRouteBinding::resolveForRoute($this->container, $route);

return call_user_func(
$this->implicitBindingCallback ?? $default, $this->container, $route, $default
);

}

/**
* Register a callback to to run after implicit bindings are substituted.
*
* @param callable $callback
* @return $this
*/
public function substituteImplicitBindingsUsing($callback)
{
$this->implicitBindingCallback = $callback;

return $this;
}

/**
Expand Down
21 changes: 21 additions & 0 deletions tests/Routing/RoutingRouteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1756,6 +1756,27 @@ public function testImplicitBindings()
$this->assertSame('taylor', $router->dispatch(Request::create('foo/taylor', 'GET'))->getContent());
}

public function testImplicitBindingsWithClosure()
{
$router = $this->getRouter();

$router->substituteImplicitBindingsUsing(function ($container, $route, $default) {
$default = $default();

$model = $route->parameter('bar');
$model->value = 'otwell';
});

$router->get('foo/{bar}', [
'middleware' => SubstituteBindings::class,
'uses' => function (RoutingTestUserModel $bar) {
return $bar->value;
},
]);

$this->assertSame('otwell', $router->dispatch(Request::create('foo/taylor', 'GET'))->getContent());
}

public function testImplicitBindingsWhereScopedBindingsArePrevented()
{
$router = $this->getRouter();
Expand Down
Loading