Skip to content

Instantly share code, notes, and snippets.

@cgray
Created April 4, 2017 03:54
Show Gist options
  • Save cgray/fc1c6ca90409c0a5b8d17f930437d596 to your computer and use it in GitHub Desktop.
Save cgray/fc1c6ca90409c0a5b8d17f930437d596 to your computer and use it in GitHub Desktop.
Given an array of placeholder values and a FastRoute uri definition build a url
<?php
function buildUrl($uri, array $params) {
$matches = [];
$pattern = '{\s* ([a-zA-Z_][a-zA-Z0-9_-]*) \s*(?:: \s* ([^{}]*(?:\{(?-1)\}[^{}]*)*))?\}';
$optionalSegments = '\[.*'.$pattern.'\]';
$uri = preg_replace_callback('~'.$optionalSegments.'~x', function($match) use ($params) {
$uri = trim($match[0], '[]');
if (isset($params[$match[1]])) {
return trim($match[0],'[]');
}
return '';
}, $uri);
return preg_replace_callback('~'.$pattern.'~x', function($match) use ($params) {
if (!isset($params[$match[1]])) {
throw new RuntimeException("'".$match[1]."' not defined in input array");
}
return $params[$match[1]];
}, $uri);
}
$uri = '/articles/{id:\d+}[/{name}]';
$params = [
'id'=>15,
'name'=>'Fred',
];
echo buildUrl($uri, $params);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment