2021-01-13 15:40:27 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
namespace ZM\Http;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
use Symfony\Component\Routing\Route;
|
|
|
|
|
use Symfony\Component\Routing\RouteCollection;
|
|
|
|
|
use ZM\Annotation\Http\Controller;
|
|
|
|
|
use ZM\Annotation\Http\RequestMapping;
|
2021-01-20 16:11:04 +08:00
|
|
|
use ZM\Console\Console;
|
2021-03-15 02:54:16 +08:00
|
|
|
use ZM\Store\LightCacheInside;
|
2021-01-13 15:40:27 +08:00
|
|
|
|
|
|
|
|
class RouteManager
|
|
|
|
|
{
|
|
|
|
|
/** @var null|RouteCollection */
|
|
|
|
|
public static $routes = null;
|
|
|
|
|
|
|
|
|
|
public static function importRouteByAnnotation(RequestMapping $vss, $method, $class, $methods_annotations) {
|
2021-02-09 17:09:09 +08:00
|
|
|
if (self::$routes === null) self::$routes = new RouteCollection();
|
2021-01-13 15:40:27 +08:00
|
|
|
|
|
|
|
|
// 拿到所属方法的类上面有没有控制器的注解
|
|
|
|
|
$prefix = '';
|
|
|
|
|
foreach ($methods_annotations as $annotation) {
|
|
|
|
|
if ($annotation instanceof Controller) {
|
|
|
|
|
$prefix = $annotation->prefix;
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
2021-01-20 16:11:04 +08:00
|
|
|
$tail = trim($vss->route, "/");
|
2021-02-09 17:09:09 +08:00
|
|
|
$route_name = $prefix . ($tail === "" ? "" : "/") . $tail;
|
|
|
|
|
Console::debug("添加路由:" . $route_name);
|
2021-01-13 15:40:27 +08:00
|
|
|
$route = new Route($route_name, ['_class' => $class, '_method' => $method]);
|
|
|
|
|
$route->setMethods($vss->request_method);
|
|
|
|
|
|
|
|
|
|
self::$routes->add(md5($route_name), $route);
|
|
|
|
|
}
|
2021-03-15 02:54:16 +08:00
|
|
|
|
|
|
|
|
public static function addStaticFileRoute($route, $path) {
|
|
|
|
|
$tail = trim($route, "/");
|
|
|
|
|
$route_name = ($tail === "" ? "" : "/") . $tail . "/{filename}";
|
|
|
|
|
Console::debug("添加静态文件路由:" . $route_name);
|
|
|
|
|
$route = new Route($route_name, ['_class' => RouteManager::class, '_method' => "onStaticRoute"]);
|
|
|
|
|
//echo $path.PHP_EOL;
|
|
|
|
|
LightCacheInside::set("static_route", $route->getPath(), $path);
|
|
|
|
|
|
|
|
|
|
self::$routes->add(md5($route_name), $route);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function onStaticRoute($params) {
|
|
|
|
|
$route_path = self::$routes->get($params["_route"])->getPath();
|
|
|
|
|
if(($path = LightCacheInside::get("static_route", $route_path)) === null) {
|
|
|
|
|
ctx()->getResponse()->endWithStatus(404);
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
unset($params["_route"]);
|
|
|
|
|
$obj = array_shift($params);
|
|
|
|
|
return new StaticFileHandler($obj, $path);
|
|
|
|
|
}
|
2021-01-13 15:40:27 +08:00
|
|
|
}
|