Skip to content

Commit

Permalink
[10.x] Add "substituteImplicitBindingsUsing" method to router (#49200)
Browse files Browse the repository at this point in the history
* Add "substituteImplicitBindingsUsing" method to router

* Remove un-used test method

* formatting

* simplify code

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
calebporzio and taylorotwell authored Nov 30, 2023
1 parent 2b9d596 commit ccf8beb
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
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

0 comments on commit ccf8beb

Please sign in to comment.