index/src/Http/Routing/ScopedRouter.php

47 lines
1.3 KiB
PHP

<?php
// ScopedRouter.php
// Created: 2024-03-28
// Updated: 2024-08-01
namespace Index\Http\Routing;
/**
* Provides a scoped router interface, automatically adds a prefix to any routes added.
*/
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
) {
if($router instanceof ScopedRouter)
$router = $router->getParentRouter();
// TODO: cleanup prefix
}
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);
}
}