Skip to content

Instantly share code, notes, and snippets.

@OO00O0O
Created October 17, 2021 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OO00O0O/8dacbfdd818267272d2714c1686f0ab3 to your computer and use it in GitHub Desktop.
Save OO00O0O/8dacbfdd818267272d2714c1686f0ab3 to your computer and use it in GitHub Desktop.
Simple regexp router
<?php declare(strict_types=1);
$routes = [
['GET /(?<something_file>[a-z][a-z0-9]{8}\.[a-z0-9]{3,4})', '...meta...'],
['GET /(?<ok>what|na)', '...meta...'],
['POST /', '...meta...'],
];
$regexp = implode('|', array_map( // could be cached
static function (int $index, array $values) {
return sprintf('^(?<_%s>%s)$', $index, str_replace('(?<', "(?<_{$index}_", $values[0]));
},
array_keys($routes),
$routes,
));
$attrs = [];
$routesIndex = matchRoute($regexp, 'GET', '/what', $attrs);
function matchRoute(string $regexp, string $method, string $path, array &$attributes = []): ?int
{
if (preg_match("#$regexp#i", "$method $path", $matches, PREG_UNMATCHED_AS_NULL) === false) {
return null;
}
$index = null;
foreach (array_filter($matches) as $key => $value) {
if (is_numeric($key) || !str_starts_with($key, '_')) {
continue;
}
$i = substr($key, 1);
if ($index === null && is_numeric($i)) {
$index = (int)$i;
continue;
}
if ($index === null || empty($value) || !str_starts_with($key, "_{$index}")) {
continue;
}
$attributes[str_replace("_{$index}_", '', $key)] = $value;
}
return $index;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment