Skip to content

Commit ccf8beb

Browse files
[10.x] Add "substituteImplicitBindingsUsing" method to router (#49200)
* Add "substituteImplicitBindingsUsing" method to router * Remove un-used test method * formatting * simplify code --------- Co-authored-by: Taylor Otwell <[email protected]>
1 parent 2b9d596 commit ccf8beb

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

src/Illuminate/Routing/Router.php

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,13 @@ class Router implements BindingRegistrar, RegistrarContract
119119
*/
120120
protected $groupStack = [];
121121

122+
/**
123+
* The registered custom implicit binding callback.
124+
*
125+
* @var array
126+
*/
127+
protected $implicitBindingCallback;
128+
122129
/**
123130
* All of the verbs supported by the router.
124131
*
@@ -949,7 +956,25 @@ public function substituteBindings($route)
949956
*/
950957
public function substituteImplicitBindings($route)
951958
{
952-
ImplicitRouteBinding::resolveForRoute($this->container, $route);
959+
$default = fn () => ImplicitRouteBinding::resolveForRoute($this->container, $route);
960+
961+
return call_user_func(
962+
$this->implicitBindingCallback ?? $default, $this->container, $route, $default
963+
);
964+
965+
}
966+
967+
/**
968+
* Register a callback to to run after implicit bindings are substituted.
969+
*
970+
* @param callable $callback
971+
* @return $this
972+
*/
973+
public function substituteImplicitBindingsUsing($callback)
974+
{
975+
$this->implicitBindingCallback = $callback;
976+
977+
return $this;
953978
}
954979

955980
/**

tests/Routing/RoutingRouteTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1756,6 +1756,27 @@ public function testImplicitBindings()
17561756
$this->assertSame('taylor', $router->dispatch(Request::create('foo/taylor', 'GET'))->getContent());
17571757
}
17581758

1759+
public function testImplicitBindingsWithClosure()
1760+
{
1761+
$router = $this->getRouter();
1762+
1763+
$router->substituteImplicitBindingsUsing(function ($container, $route, $default) {
1764+
$default = $default();
1765+
1766+
$model = $route->parameter('bar');
1767+
$model->value = 'otwell';
1768+
});
1769+
1770+
$router->get('foo/{bar}', [
1771+
'middleware' => SubstituteBindings::class,
1772+
'uses' => function (RoutingTestUserModel $bar) {
1773+
return $bar->value;
1774+
},
1775+
]);
1776+
1777+
$this->assertSame('otwell', $router->dispatch(Request::create('foo/taylor', 'GET'))->getContent());
1778+
}
1779+
17591780
public function testImplicitBindingsWhereScopedBindingsArePrevented()
17601781
{
17611782
$router = $this->getRouter();

0 commit comments

Comments
 (0)