request->baseUrl; $routes = require_once('routes.php'); $hostUrl = Yii::$app->request->getHostInfo(); /** * Class Router */ class Router { public $routes = []; public $redirects = []; public $paths = []; public $icons = [ '欢迎' => 'glyphicon glyphicon-home', '厂商' => 'glyphicon glyphicon-user', '序列号' => 'glyphicon glyphicon-shopping-cart', '版本' => 'glyphicon glyphicon-qrcode', '项目' => 'glyphicon glyphicon-hdd', '机器型号' => 'glyphicon glyphicon-print', '生产日期' => 'glyphicon glyphicon-bullhorn', '数据统计' => 'glyphicon glyphicon-stats', '发票' => 'glyphicon glyphicon-envelope', '系统' => 'glyphicon glyphicon-hdd', '设置' => 'glyphicon glyphicon-cog', '自动化' => 'glyphicon glyphicon-time', '账号' => 'glyphicon glyphicon-user', ]; /** * Router constructor. * @param array $routes */ public function __construct(array $routes) { $this->routes = $routes; $this->formatRoutes($this->routes); $this->paths = $this->process($this->routes); } /** * @param array $routes */ private function formatRoutes(array &$routes) { foreach ($routes as $i => &$route){ $route['icon'] = ''; if(isset($route['label'])){ $route['icon'] = $this->getIcon($route['label']); } if(isset($route['routes']) && is_array($route['routes'])){ $route['children'] = $route['routes']; unset($route['routes']); $this->formatRoutes($route['children']); } } } private function getIcon(string $label) { return isset($this->icons[$label]) ? $this->icons[$label] : ''; } /** * @param array $routes * @param array $paths * @param array $parents * @param int $level * @return array */ private function process(array $routes, $paths = [], $parents = [], $level = 0) { foreach ($routes as $i => $route){ /** * 处理redirects */ if(isset($route['redirect'])) { $this->redirects[$route['path']] = $route['redirect']; continue; } /** * 处理paths */ if($level == 0){ $parents = []; } if(isset($route['children']) && is_array($route['children'])){ $parents[] = $route['path']; $paths = $this->process($route['children'], $paths, $parents, $level+1); } else { $paths[$route['path']] = $parents; } } return $paths; } /** * @return array */ public function paths() { foreach ($this->paths as $key => $value){ array_push($value, $key); $this->paths[$key] = $value; } return $this->paths; } /** * @return array */ public function routes() { return $this->routes; } /** * @return array */ public function redirects() { return $this->redirects; } } $router = new Router($routes); $routes = $router->routes(); ?>