123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174 |
- <?php
- namespace Typecho;
- use Typecho\Router\Parser;
- use Typecho\Router\Exception as RouterException;
- class Router
- {
-
- public static $current;
-
- private static $routingTable = [];
-
- public static function match(?string $pathInfo, $parameter = null)
- {
- foreach (self::$routingTable as $key => $route) {
- if (preg_match($route['regx'], $pathInfo, $matches)) {
- self::$current = $key;
- try {
-
- $params = null;
- if (!empty($route['params'])) {
- unset($matches[0]);
- $params = array_combine($route['params'], $matches);
- }
- return Widget::widget($route['widget'], $parameter, $params);
- } catch (\Exception $e) {
- if (404 == $e->getCode()) {
- Widget::destroy($route['widget']);
- continue;
- }
- throw $e;
- }
- }
- }
- return false;
- }
-
- public static function dispatch()
- {
-
- $pathInfo = Request::getInstance()->getPathInfo();
- foreach (self::$routingTable as $key => $route) {
- if (preg_match($route['regx'], $pathInfo, $matches)) {
- self::$current = $key;
- try {
-
- $params = null;
- if (!empty($route['params'])) {
- unset($matches[0]);
- $params = array_combine($route['params'], $matches);
- }
- $widget = Widget::widget($route['widget'], null, $params);
- if (isset($route['action'])) {
- $widget->{$route['action']}();
- }
- return;
- } catch (\Exception $e) {
- if (404 == $e->getCode()) {
- Widget::destroy($route['widget']);
- continue;
- }
- throw $e;
- }
- }
- }
-
- throw new RouterException("Path '{$pathInfo}' not found", 404);
- }
-
- public static function url(string $name, ?array $value = null, ?string $prefix = null): string
- {
- $route = self::$routingTable[$name];
-
- $pattern = [];
- foreach ($route['params'] as $row) {
- $pattern[$row] = $value[$row] ?? '{' . $row . '}';
- }
- return Common::url(vsprintf($route['format'], $pattern), $prefix);
- }
-
- public static function setRoutes($routes)
- {
- if (isset($routes[0])) {
- self::$routingTable = $routes[0];
- } else {
-
- $parser = new Parser($routes);
- self::$routingTable = $parser->parse();
- }
- }
-
- public static function get(string $routeName)
- {
- return self::$routingTable[$routeName] ?? null;
- }
- }
|