Created
January 15, 2020 14:47
-
-
Save midorikocak/33e09cf0c1875577888015fa4081dfc7 to your computer and use it in GitHub Desktop.
URI Wildcard Matching
This file contains 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 | |
declare(strict_types=1); | |
/* | |
* Test if pattern is like users/{id}/comments/{comment_id} | |
* and create variables if url is satisfies pattern | |
* | |
* example: | |
* pattern: users/{id}/comments/{comment_id} | |
* uri: /users/4/comments/5 | |
* return: [ | |
* 'pattern' => "users/{id}/comments/{comment_id}", | |
* 'uri' => "/users/4/comments/5", | |
* 'vars' => ['id','comment_id'], | |
* 'values' => [4, 5], | |
* ] | |
*/ | |
function compareUri($uri, $pattern) | |
{ | |
// does pattern have brackets? | |
$hasBrackets = preg_match_all('/{(.+)}/', $pattern, $vars); | |
if ($hasBrackets) { | |
// replace users/{id}/comments/{comment_id} into regex | |
$newPattern = preg_replace('/{.+?}/m', '([^/{}]+)', $pattern); | |
// if a url is like /users/4/comments/5 | |
$passesNewPattern = preg_match("~^".$newPattern."$~", $uri, $values); | |
if ($passesNewPattern) { | |
//remove first array item | |
array_shift($values); | |
return [ | |
'pattern' => $pattern, | |
'uri' => $uri, | |
'vars' => $vars, | |
'values' => array_values($values), | |
]; | |
} | |
} | |
return []; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment