forked from PHP/Router
Optimize $params using array_reduce
This commit is contained in:
parent
49819b41bd
commit
4df658fc1c
|
@ -78,31 +78,33 @@ class SegmentRouter implements RouterInterface
|
||||||
}
|
}
|
||||||
|
|
||||||
// params will hold any dynamic segments we find
|
// params will hold any dynamic segments we find
|
||||||
$params = [];
|
$params = array_reduce(
|
||||||
|
explode('/', trim($uri, '/')),
|
||||||
// We'll split up the URI into segments and traverse the node tree
|
function ($carry, $segment) use (&$node) {
|
||||||
foreach (explode('/', trim($uri, '/')) as $segment) {
|
if (isset($node[$segment])) {
|
||||||
// if there is a node for this segment, move to it
|
$node = $node[$segment];
|
||||||
if (isset($node[$segment])) {
|
} elseif (isset($node[':x'])) {
|
||||||
$node = $node[$segment];
|
$carry[] = $segment;
|
||||||
continue;
|
$node = $node[':x'];
|
||||||
}
|
} else {
|
||||||
|
throw new \Exception('404');
|
||||||
// if there is a dynamic segment, move to it and store the value
|
}
|
||||||
if (isset($node[':x'])) {
|
return $carry;
|
||||||
$params[] = $segment;
|
},
|
||||||
$node = $node[':x'];
|
[]
|
||||||
continue;
|
);
|
||||||
}
|
|
||||||
|
|
||||||
// if we can't find a node for this segment, return 404
|
|
||||||
return ['code' => 404, 'handler' => null, 'params' => []];
|
|
||||||
}
|
|
||||||
|
|
||||||
// if we found a handler for the method, return it and any params. if not, return a 405
|
// if we found a handler for the method, return it and any params. if not, return a 405
|
||||||
return isset($node[$method])
|
return isset($node[$method])
|
||||||
? ['code' => 200, 'handler' => $node[$method], 'params' => $params ?? []]
|
? [
|
||||||
: ['code' => 405, 'handler' => null, 'params' => []];
|
'code' => 200,
|
||||||
|
'handler' => $node[$method],
|
||||||
|
'params' => $params ?? []]
|
||||||
|
: [
|
||||||
|
'code' => 405,
|
||||||
|
'handler' => null,
|
||||||
|
'params' => []
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
Loading…
Reference in New Issue
Block a user