index/src/Http/Routing/ScopedRouter.php

48 lines
1.3 KiB
PHP
Raw Normal View History

2024-03-28 20:01:34 +00:00
<?php
// ScopedRouter.php
// Created: 2024-03-28
// Updated: 2024-08-01
2024-03-28 20:01:34 +00:00
namespace Index\Http\Routing;
/**
* Provides a scoped router interface, automatically adds a prefix to any routes added.
*/
2024-03-28 20:01:34 +00:00
class ScopedRouter implements IRouter {
use RouterTrait;
/**
* @param IRouter $router Underlying router.
* @param string $prefix Base path to use as a prefix.
*/
public function __construct(
private IRouter $router,
private string $prefix
) {
2024-03-28 20:01:34 +00:00
if($router instanceof ScopedRouter)
$router = $router->getParentRouter();
// TODO: cleanup prefix
2024-03-28 20:01:34 +00:00
}
private function getParentRouter(): IRouter {
return $this->router;
}
public function scopeTo(string $prefix): IRouter {
return $this->router->scopeTo($this->prefix . $prefix);
}
public function add(string $method, string $path, callable $handler): void {
$this->router->add($method, $this->prefix . $path, $handler);
}
public function use(string $path, callable $handler): void {
$this->router->use($this->prefix . $path, $handler);
}
public function resolve(string $method, string $path): ResolvedRouteInfo {
return $this->router->resolve($method, $this->prefix . $path);
}
}