mirror of
https://github.com/flarum/core.git
synced 2025-07-21 08:41:17 +02:00
Allow overriding routes (#2577)
This commit is contained in:
@@ -30,6 +30,16 @@ class RouteCollection
|
||||
*/
|
||||
protected $routeParser;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $routes = [];
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $pendingRoutes = [];
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->dataGenerator = new DataGenerator\GroupCountBased;
|
||||
@@ -63,19 +73,50 @@ class RouteCollection
|
||||
|
||||
public function addRoute($method, $path, $name, $handler)
|
||||
{
|
||||
$routeDatas = $this->routeParser->parse($path);
|
||||
|
||||
foreach ($routeDatas as $routeData) {
|
||||
$this->dataGenerator->addRoute($method, $routeData, ['name' => $name, 'handler' => $handler]);
|
||||
if (isset($this->routes[$method][$name])) {
|
||||
throw new \RuntimeException("Route $name on method $method already exists");
|
||||
}
|
||||
|
||||
$this->reverse[$name] = $routeDatas;
|
||||
$this->routes[$method][$name] = $this->pendingRoutes[$method][$name] = compact('path', 'handler');
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function removeRoute(string $method, string $name): self
|
||||
{
|
||||
unset($this->routes[$method][$name], $this->pendingRoutes[$method][$name]);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
protected function applyRoutes(): void
|
||||
{
|
||||
foreach ($this->pendingRoutes as $method => $routes) {
|
||||
foreach ($routes as $name => $route) {
|
||||
$routeDatas = $this->routeParser->parse($route['path']);
|
||||
|
||||
foreach ($routeDatas as $routeData) {
|
||||
$this->dataGenerator->addRoute($method, $routeData, ['name' => $name, 'handler' => $route['handler']]);
|
||||
}
|
||||
|
||||
$this->reverse[$name] = $routeDatas;
|
||||
}
|
||||
}
|
||||
|
||||
$this->pendingRoutes = [];
|
||||
}
|
||||
|
||||
public function getRoutes(): array
|
||||
{
|
||||
return $this->routes;
|
||||
}
|
||||
|
||||
public function getRouteData()
|
||||
{
|
||||
if (! empty($this->pendingRoutes)) {
|
||||
$this->applyRoutes();
|
||||
}
|
||||
|
||||
return $this->dataGenerator->getData();
|
||||
}
|
||||
|
||||
@@ -88,6 +129,10 @@ class RouteCollection
|
||||
|
||||
public function getPath($name, array $parameters = [])
|
||||
{
|
||||
if (! empty($this->pendingRoutes)) {
|
||||
$this->applyRoutes();
|
||||
}
|
||||
|
||||
if (isset($this->reverse[$name])) {
|
||||
$maxMatches = 0;
|
||||
$matchingParts = $this->reverse[$name][0];
|
||||
|
Reference in New Issue
Block a user