Skip to content

Commit

Permalink
add hook for missing named route resolution
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorotwell committed Aug 14, 2023
1 parent 8bea688 commit 1169dbc
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/Illuminate/Routing/UrlGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,13 @@ class UrlGenerator implements UrlGeneratorContract
*/
protected $keyResolver;

/**
* The missing named route resolver callable.
*
* @var callable
*/
protected $missingNamedRouteResolver;

/**
* The callback to use to format hosts.
*
Expand Down Expand Up @@ -464,6 +471,11 @@ public function route($name, $parameters = [], $absolute = true)
return $this->toRoute($route, $parameters, $absolute);
}

if (! is_null($this->missingNamedRouteResolver) &&
! is_null($url = call_user_func($this->missingNamedRouteResolver, $name, $parameters, $absolute))) {
return $url;
}

throw new RouteNotFoundException("Route [{$name}] not defined.");
}

Expand Down Expand Up @@ -820,6 +832,19 @@ public function withKeyResolver(callable $keyResolver)
return (clone $this)->setKeyResolver($keyResolver);
}

/**
* Set the callback that should be used to attempt to resolve missing named routes.
*
* @param callable $missingNamedRouteResolver
* @return $this
*/
public function resolveMissingNamedRoutesUsing(callable $missingNamedRouteResolver)
{
$this->missingNamedRouteResolver = $missingNamedRouteResolver;

return $this;
}

/**
* Get the root controller namespace.
*
Expand Down
12 changes: 12 additions & 0 deletions tests/Routing/RoutingUrlGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -908,6 +908,18 @@ public function testSignedUrlWithKeyResolver()
$this->assertTrue($url2->hasValidSignature($request));
$this->assertFalse($url->hasValidSignature($request));
}

public function testMissingNamedRouteResolution()
{
$url = new UrlGenerator(
new RouteCollection,
Request::create('http://www.foo.com/')
);

$url->resolveMissingNamedRoutesUsing(fn ($name, $parameters, $absolute) => 'test-url');

$this->assertSame('test-url', $url->route('foo'));
}
}

class RoutableInterfaceStub implements UrlRoutable
Expand Down

0 comments on commit 1169dbc

Please sign in to comment.