Skip to content

Commit

Permalink
add URL pattern template replacement function, per #3
Browse files Browse the repository at this point in the history
  • Loading branch information
mindplay-dk committed Aug 10, 2016
1 parent 0ce044c commit dc2b01c
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 2 deletions.
26 changes: 26 additions & 0 deletions src/UrlHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,30 @@ protected function slug($value, $max_length = null) {

return substr($clean, 0, $max_length ?: $this->slug_max_length);
}

/**
* Replaces a route template, with placeholders such as "<foo>" or "<foo:bar>", with
* a set of replacement values.
*
* @param string $template route template
* @param array $values map where token name => replacement value
*
* @return string
*/
protected function replace($template, $values)
{
return preg_replace_callback(
Router::PARAM_PATTERN,
function ($matches) use ($values) {
$name = $matches[1];

if (!isset($values[$name])) {
throw new InvalidArgumentException("missing replacement value for token: {$name}");
}

return $values[$name];
},
$template
);
}
}
41 changes: 39 additions & 2 deletions test/test.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,21 @@ public function test($input, $expected)
}
}

class ReplaceTester extends UrlHelper
{
/**
* @param string $template
* @param array $tokens
* @param string $expected
*
* @return string
*/
public function test($template, $tokens, $expected)
{
eq($this->replace($template, $tokens), $expected);
}
}

class SampleUrlHelper extends UrlHelper
{
/**
Expand All @@ -40,7 +55,7 @@ class SampleController implements Controller
{
public function run($id, $title)
{
return array($id, $title);
return [$id, $title];
}
}

Expand Down Expand Up @@ -168,7 +183,7 @@ function () {
function () use ($router) {
$router->resolve('GET', '/users/bob?crazy-yo');
},
'#^'.preg_quote('unexpected query string in $url: /users/bob?crazy-yo').'$#'
'#^' . preg_quote('unexpected query string in $url: /users/bob?crazy-yo') . '$#'
);
}
);
Expand Down Expand Up @@ -331,6 +346,28 @@ function () use ($url) {
}
);

test(
'can replace tokens in templates',
function () {
$replace = new ReplaceTester();

$replace->test('foo/<bar>', ['bar' => 'hello'], 'foo/hello');

$replace->test('foo/<bar:slug>', ['bar' => 'hello'], 'foo/hello');

$replace->test('foo/<bar:slug>/<baz:\w+>', ['bar' => 'hello', 'baz' => 'world'], 'foo/hello/world');

expect(
'InvalidArgumentException',
'should throw for missing replacements token',
function () use ($replace) {
$replace->test('foo/<bar>/<baz>', ['bar' => 'hello'], 'foo/hello/');
},
'/for token: baz/'
);
}
);

test(
'can use wildcard in patterns',
function () {
Expand Down

0 comments on commit dc2b01c

Please sign in to comment.