mirror of
https://github.com/flarum/core.git
synced 2025-07-21 08:41:17 +02:00
Fix optional parameters in url generator (#2246)
* Fix route collection getting wrong path when optional parameters present, add unit tests
This commit is contained in:
committed by
GitHub
parent
52394776ff
commit
a215fc9ed5
@@ -11,6 +11,7 @@ namespace Flarum\Http;
|
||||
|
||||
use FastRoute\DataGenerator;
|
||||
use FastRoute\RouteParser;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
class RouteCollection
|
||||
{
|
||||
@@ -88,10 +89,25 @@ class RouteCollection
|
||||
public function getPath($name, array $parameters = [])
|
||||
{
|
||||
if (isset($this->reverse[$name])) {
|
||||
$parts = $this->reverse[$name][0];
|
||||
array_walk($parts, [$this, 'fixPathPart'], $parameters);
|
||||
$maxMatches = 0;
|
||||
$matchingParts = $this->reverse[$name][0];
|
||||
|
||||
return '/'.ltrim(implode('', $parts), '/');
|
||||
// For a given route name, we want to choose the option that best matches the given parameters.
|
||||
// Each routing option is an array of parts. Each part is either a constant string
|
||||
// (which we don't care about here), or an array where the first element is the parameter name
|
||||
// and the second element is a regex into which the parameter value is inserted, if the parameter matches.
|
||||
foreach ($this->reverse[$name] as $parts) {
|
||||
foreach ($parts as $i => $part) {
|
||||
if (is_array($part) && Arr::exists($parameters, $part[0]) && $i > $maxMatches) {
|
||||
$maxMatches = $i;
|
||||
$matchingParts = $parts;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
array_walk($matchingParts, [$this, 'fixPathPart'], $parameters);
|
||||
|
||||
return '/'.ltrim(implode('', $matchingParts), '/');
|
||||
}
|
||||
|
||||
throw new \RuntimeException("Route $name not found");
|
||||
|
Reference in New Issue
Block a user