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

[5.4] Default named parameters in UrlGenerator #16736

Merged
merged 3 commits into from
Dec 11, 2016
Merged
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
47 changes: 45 additions & 2 deletions src/Illuminate/Routing/UrlGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,13 @@ class UrlGenerator implements UrlGeneratorContract
'%25' => '%',
];

/**
* Default named parameters.
*
* @var array
*/
protected $defaultNamedParameters = [];

/**
* Create a new URL Generator instance.
*
Expand Down Expand Up @@ -297,6 +304,34 @@ protected function getScheme($secure)
return $secure ? 'https://' : 'http://';
}

/**
* Get the default named parameters.
*
* @return array
*/
public function getDefaultNamedParameters()
{
return $this->defaultNamedParameters;
}

/**
* Set the default named parameters.
*
* @param string|array $key
* @param mixed $value
* @return void
*/
public function setDefaultNamedParameters($key, $value = null)
{
if (is_array($key)) {
foreach ($key as $k => $v) {
$this->defaultNamedParameters[$k] = $v;
}
} else {
$this->defaultNamedParameters[$key] = $value;
}
}

/**
* Force the schema for URLs.
*
Expand Down Expand Up @@ -403,8 +438,16 @@ protected function replaceRouteParameters($path, array &$parameters)
*/
protected function replaceNamedParameters($path, &$parameters)
{
return preg_replace_callback('/\{(.*?)\??\}/', function ($m) use (&$parameters) {
return isset($parameters[$m[1]]) ? Arr::pull($parameters, $m[1]) : $m[0];
$defaultNamedParameters = $this->getDefaultNamedParameters();

return preg_replace_callback('/\{(.*?)\??\}/', function ($m) use (&$parameters, $defaultNamedParameters) {
if (isset($parameters[$m[1]])) {
return Arr::pull($parameters, $m[1]);
} elseif (isset($defaultNamedParameters[$m[1]])) {
return $defaultNamedParameters[$m[1]];
} else {
return $m[0];
}
}, $path);
}

Expand Down