Created
April 4, 2017 03:54
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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