示例#1
1
 public function __construct($routes = null, $middleWare = null)
 {
     $rootDir = Config::getRootDir();
     /**
      * Get Config from Module Config directory
      * File name must be Router.php
      */
     if (empty($routes)) {
         if (!empty(Config::getConfig('cachePath'))) {
             $cacheDir = Config::getConfig('cachePath');
         } else {
             $cacheDir = Config::getRootDir() . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'cache';
         }
         $cacheFile = $cacheDir . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'router.php';
         if (true === Config::getConfig('cache') && file_exists($cacheFile)) {
             $routes = (require_once $cacheFile);
         } else {
             $directory = new \RecursiveDirectoryIterator($rootDir, \RecursiveDirectoryIterator::KEY_AS_FILENAME | \RecursiveDirectoryIterator::CURRENT_AS_FILEINFO);
             $files = new \RegexIterator(new \RecursiveIteratorIterator($directory), '#^Router\\.php$#', \RegexIterator::MATCH, \RegexIterator::USE_KEY);
             $routerConfiguration = [];
             foreach ($files as $filePath) {
                 $moduleRouterConfiguration = (require_once $filePath->getPathname());
                 $routerConfiguration = array_merge($routerConfiguration, $moduleRouterConfiguration);
             }
             $routes = $routerConfiguration;
         }
         if (true === Config::getConfig('cache')) {
             if (!file_exists($cacheFile)) {
                 touch($cacheFile);
             }
             $str = "<?php\nreturn " . var_export($routes, true) . ";\n";
             file_put_contents($cacheFile, $str);
         }
     }
     $this->routes = $routes;
     $this->request = ServerRequestFactory::fromGlobals();
     $dir = Config::getRootDir() . DS . 'storage' . DS . 'cache' . DS;
     $this->middleWare = $middleWare;
     if (true === Config::getConfig('cache')) {
         $this->dispatcher = \FastRoute\cachedDispatcher(function (\FastRoute\RouteCollector $r) {
             foreach ($this->routes as $k => $v) {
                 $method = explode('|', $v['method']);
                 $v['path'] = !isset($v['path']) ? $v['match'] : $v['path'];
                 if ($v['path'] !== '/' && substr($v['path'], -1) == '/') {
                     $v['path'] = substr($v['path'], 0, -1);
                 }
                 if (count($method) > 1) {
                     foreach ($method as $key => $m) {
                         $r->addRoute($m, $v['path'], $v['controller']);
                     }
                 } else {
                     $r->addRoute($v['method'], $v['path'], $v['controller']);
                 }
             }
         }, ['cacheFile' => $dir . 'route.cache', 'cacheDisabled' => false]);
     } else {
         $this->dispatcher = \FastRoute\simpleDispatcher(function (\FastRoute\RouteCollector $r) {
             foreach ($this->routes as $k => $v) {
                 $method = explode('|', $v['method']);
                 $v['path'] = !isset($v['path']) ? $v['match'] : $v['path'];
                 if ($v['path'] !== '/' && substr($v['path'], -1) == '/') {
                     $v['path'] = substr($v['path'], 0, -1);
                 }
                 if (count($method) > 1) {
                     foreach ($method as $key => $m) {
                         $r->addRoute($m, $v['path'], $v['controller']);
                     }
                 } else {
                     $r->addRoute($v['method'], $v['path'], $v['controller']);
                 }
             }
         });
     }
     return $this;
 }
示例#2
0
 /**
  * @param RequestInterface $request A request.
  * @return ResolvedRequestInterface
  * @throws OutOfRangeException
  * @throws Exception
  */
 public function route(RequestInterface $request)
 {
     if (!is_null($this->cachePath)) {
         $dispatcher = \FastRoute\cachedDispatcher(function (RouteCollector $collector) {
             foreach ($this->routes as $route) {
                 $collector->addRoute($route->getRequestType(), $route->getUri(), serialize($route));
             }
         }, ['cacheFile' => $this->cachePath]);
     } else {
         // Add routes to the route collector.
         $dispatcher = \FastRoute\simpleDispatcher(function (RouteCollector $collector) {
             foreach ($this->routes as $route) {
                 $collector->addRoute($route->getRequestType(), $route->getUri(), serialize($route));
             }
         });
     }
     // Dispatch the route.
     $route_info = $dispatcher->dispatch($request->getMethod(), $request->getUriPath());
     // Handle the route depending on the response type.
     switch ($route_info[0]) {
         // Route not found.
         case Dispatcher::NOT_FOUND:
             throw new OutOfRangeException("No route matched the given URI.");
             // Method not allowed for the specified route.
         // Method not allowed for the specified route.
         case Dispatcher::METHOD_NOT_ALLOWED:
             throw new Exception("Method not allowed.");
             // Route found.
         // Route found.
         case Dispatcher::FOUND:
             $route = $route_info[1];
             $params = $route_info[2];
             return new ResolvedRequest($request, unserialize($route), $params);
     }
 }
示例#3
0
 public function __construct()
 {
     $this->alias();
     $dispatcher = \FastRoute\cachedDispatcher(function (RouteCollector $r) {
         include BASE_PATH . '/config/routes.php';
     }, ['cacheFile' => BASE_PATH . '/app/cache/route.cache', 'cacheDisabled' => APP_ENVIRONMENT == 'develop' ? true : false]);
     $this->dispatcher = $dispatcher;
 }
 /**
  * @param  Pimple\Container $app
  * @return void
  */
 public function register(Container $app)
 {
     $config = $this->config;
     // Get the route bindings
     require_once $config['app_path'] . '/Http/bindings.php';
     // Using the cached dispatcher we can't use Closures as the function. Switch to the simple
     // dispatcher if Closures are necessary for some reason
     $app['dispatcher'] = \FastRoute\cachedDispatcher(function (Collector $r) use($app, $config) {
         require_once $config['app_path'] . '/Http/routes.php';
     }, ['cacheFile' => $config['cache_path'] . '/cache/routes.cache', 'cacheDisabled' => env('APP_DEBUG'), 'dispatcher' => Dispatcher::class, 'routeCollector' => Collector::class]);
 }
示例#5
0
 private function loadRouter()
 {
     $callable = function (RouteCollector $r) {
         foreach ($this->routes as $routeStruct) {
             list($httpMethod, $uri, $handler) = $routeStruct;
             $r->addRoute($httpMethod, $uri, $handler);
         }
     };
     return $this->canSerializeRoutes ? \FastRoute\cachedDispatcher($callable, ['cacheFile' => $this->options['routing.cache_file'], 'cacheDisabled' => $this->options['app.debug']]) : \FastRoute\simpleDispatcher($callable);
 }
示例#6
0
文件: App.php 项目: sydes/sydes
 private function sendRequestThroughRouter($request)
 {
     $dispatcher = \FastRoute\cachedDispatcher(function (\FastRoute\RouteCollector $r) {
         $r->addRoute('GET', '/page/{id:[0-9]+}', 'test/page');
         $r->addRoute('GET', '/notfound', 'test/notfound');
         $r->addRoute('GET', '/forbidden', 'test/forbidden');
         $r->addRoute('GET', '/ajax', 'test/ajax');
         $r->addRoute('GET', '/string.txt', 'test/string');
         $r->addRoute('GET', '/export', 'test/export');
         $r->addRoute('GET', '/html', 'test/html');
         $r->addRoute('GET', '/nool', 'test/nool');
         $r->addRoute('GET', '/moved', 'test/moved');
         $r->addRoute('GET', '/update', 'test/notifyAfterRedirect');
         $r->addRoute('GET', '/store', 'test/alertAfterRedirect');
         $r->addRoute('GET', '/ajaxupdate', 'test/ajaxNotify');
         $r->addRoute('GET', '/ajaxstore', 'test/ajaxAlert');
         $r->addRoute('GET', '/refresh', 'test/ajaxRefresh');
         $r->addRoute('GET', '/refresh2', 'test/refreshAndNotify');
         $r->addRoute('GET', '/random', 'test/random');
         $r->addRoute('GET', '/', 'test/index');
         $r->addRoute('GET', '/admin', 'test/adminMain');
         $r->addRoute('GET', '/admin/pages', 'test/adminPages');
         $r->addRoute('GET', '/login', 'user/loginForm');
         $r->addRoute('POST', '/login', 'user/login');
         $r->addRoute('GET', '/install', 'utils/signUpForm');
         $r->addRoute('POST', '/install', 'utils/signUp');
         $r->addRoute('GET', '/admin/sites/add', 'sites/addForm');
         $r->addRoute('POST', '/admin/sites/add', 'sites/add');
     }, ['cacheFile' => DIR_CACHE . '/routes.cache']);
     $routeInfo = $dispatcher->dispatch($request->method, $request->url);
     if ($routeInfo[0] == \FastRoute\Dispatcher::FOUND) {
         $parts = explode('/', $routeInfo[1]);
         $vars = $routeInfo[2];
     } else {
         //TODO try to find predefined urls in database
         if (1) {
             throw new NotFoundHttpException();
         }
         $parts = explode('/', 'test/page/42');
         $vars = array_slice($parts, 2);
     }
     $name = $parts[0];
     $class = ucfirst($parts[0]) . 'Controller';
     $method = $parts[1];
     if (null === ($path = findExt('module', $name))) {
         trigger_error(sprintf(t('module_folder_not_found'), $name), E_USER_ERROR);
     }
     include $path . '/index.php';
     $instance = new $class();
     return call_user_func_array([$instance, $method], $vars);
 }
示例#7
0
 /**
  * Constructor
  *
  * @param string $path - path to yml config file
  * @param Validator $validator - validator object with available roles, example: [1, 2, 3]
  * @param array $options - array of options. Currently available: cacheFile (path), resourceRegex
  * @throws AclException
  */
 public function __construct($path, Validator $validator, $options = [])
 {
     $this->validator = $validator;
     $this->logger = new NullLogger();
     try {
         // check if resourceRegex is present
         if (isset($options['resourceRegex'])) {
             $this->resourceRegex = $options['resourceRegex'];
         }
         // create anonymous function to build rules
         $buildRulesData = function (RouteCollector $r) {
             foreach ($this->config as $regex => $routeData) {
                 $routePart = '';
                 if ($this->validator->isTypeResource($routeData)) {
                     $routePart = $this->resourceRegex;
                 }
                 foreach ($routeData as $method => $data) {
                     if (in_array($method, $this->availableMethods)) {
                         $r->addRoute($method, "{$regex}{$routePart}", [$regex => $routeData]);
                     }
                 }
             }
         };
         // if cache file option is present, then use cache.
         if (isset($options['cacheFile'])) {
             $this->logger->debug("cacheFile option is set, checking for file.");
             if (!file_exists($options['cacheFile'])) {
                 $this->logger->debug("No file exist, try to read from {$options['cacheFile']}.");
                 $this->config = $this->readConfigurationFile($path);
             }
             $this->dispatcher = \FastRoute\cachedDispatcher($buildRulesData, $options);
         } else {
             $this->config = $this->readConfigurationFile($path);
             $this->dispatcher = \FastRoute\simpleDispatcher($buildRulesData);
         }
         $this->logger->debug("ACL is ready to verify.");
     } catch (\Exception $e) {
         throw new AclException($e->getMessage());
     }
 }
示例#8
0
 /**
  * @return FastRoute\Dispatcher|FastRoute\Dispatcher\GroupCountBased
  */
 public function getDispatcher()
 {
     $cacheKey = $this->modx->getOption(xPDO::OPT_CACHE_PATH) . 'default/';
     if (isset($this->config['fastrouter_cache_key'])) {
         $cacheKey .= $this->config['fastrouter_cache_key'];
     } else {
         $cacheKey .= $this->modx->getOption('virtualpage_fastrouter_cache_key', null, 'virtualpage/event/');
     }
     if (!isset($this->dispatcher[$this->event])) {
         $this->dispatcher[$this->event] = FastRoute\cachedDispatcher(function (FastRoute\RouteCollector $router) {
             $this->getRoutes($router);
         }, array('cacheFile' => $cacheKey . '/' . $this->event . '.cache.php'));
     }
     return $this->dispatcher[$this->event];
 }
示例#9
0
 /**
  * @return \FastRoute\Dispatcher
  */
 protected function createDispatcher()
 {
     if ($this->dispatcher) {
         return $this->dispatcher;
     }
     $routeDefinitionCallback = function (RouteCollector $r) {
         foreach ($this->getRoutes() as $route) {
             $r->addRoute($route->getMethods(), $route->getPattern(), $route->getIdentifier());
         }
     };
     if ($this->cacheFile) {
         $this->dispatcher = \FastRoute\cachedDispatcher($routeDefinitionCallback, ['routeParser' => $this->routeParser, 'cacheFile' => $this->cacheFile]);
     } else {
         $this->dispatcher = \FastRoute\simpleDispatcher($routeDefinitionCallback, ['routeParser' => $this->routeParser]);
     }
     return $this->dispatcher;
 }
示例#10
0
 /**
  * @return \FastRoute\Dispatcher
  */
 private function createDispatcher()
 {
     $routeDefinition = function (RouteCollector $collector) {
         foreach ($this->routeCollection->getRoutes() as $route) {
             $collector->addRoute($route->methods, $route->path, $route);
         }
     };
     if (isset($this['route.cache_file'])) {
         return \FastRoute\cachedDispatcher($routeDefinition, ['cacheFile' => $this['route.cache_file'], 'cacheDisabled' => $this['debug']]);
     } else {
         return \FastRoute\simpleDispatcher($routeDefinition);
     }
 }
示例#11
0
文件: Router.php 项目: otak/maestro
 /**
  * Inits dispatcher according to routes.
  *
  * @chainable
  * @return self
  */
 public function init()
 {
     $routes = $this->_routes;
     $this->_dispatcher = \FastRoute\cachedDispatcher(function (RouteCollector $routeCollector) use($routes) {
         foreach ($routes as &$r) {
             foreach ($r['verbs'] as $verb => $handler) {
                 $routeCollector->addRoute($verb, $r['pattern'], $handler);
             }
         }
     }, array('cacheFile' => self::CACHE_FILE_LOCATION, 'cacheDisabled' => 'development' === Maestro::gi()->get('env')));
     return $this;
 }
示例#12
0
 /**
  * @return Dispatcher
  */
 private function configureRouterDispatcher()
 {
     $routeDefinitionCallback = function (RouteCollector $routeCollector) {
         $configurator = new ControllerConfigurator($this->options->basePath, $routeCollector);
         foreach ($this->controllers as $controller) {
             $configurator->configure($controller);
         }
     };
     $options = ['cacheFile' => $this->options->cacheDir . '/route.cache', 'cacheDisabled' => $this->options->devMode];
     return \FastRoute\cachedDispatcher($routeDefinitionCallback, $options);
 }
 /**
  * Returns an instance of the FastRoute dispatcher.
  * @param array $routes The array of specified routes.
  * @return FastRoute\Dispatcher The dispatcher to use.
  */
 private function getDispatcher($routes)
 {
     $verbs = self::$allHttpVerbs;
     $f = function (RouteCollector $collector) use($routes, $verbs) {
         foreach ($routes as $pattern => $route) {
             if (is_array($route)) {
                 foreach ($route as $verb => $callback) {
                     $collector->addRoute(strtoupper($verb), $pattern, $callback);
                 }
             } else {
                 foreach ($verbs as $verb) {
                     $collector->addRoute($verb, $pattern, $route);
                 }
             }
         }
     };
     $options = $this->getOptions();
     $cacheData = array();
     if (isset($options[self::KEY_CACHE])) {
         $cacheData = (array) $options[self::KEY_CACHE];
     }
     if (empty($cacheData)) {
         return \FastRoute\simpleDispatcher($f);
     } else {
         return \FastRoute\cachedDispatcher($f, $cacheData);
     }
 }
示例#14
0
 private static function initRouter()
 {
     self::set('dispatcher', function () {
         return \FastRoute\cachedDispatcher(function (RouteCollector $r) {
             $router = self::$resources['routing'];
             foreach ($router as $rule) {
                 list($controller, $action) = explode(':', $rule['controller']);
                 foreach ($rule['methods'] as $method) {
                     $routeData = $rule;
                     $routeData['controller'] = strtolower($controller);
                     $routeData['action'] = $action;
                     $routeData['actionName'] = $action . 'Action';
                     $routeData['className'] = '\\VJ\\Controller\\' . ucfirst(strtolower($controller)) . 'Controller';
                     $r->addRoute($method, $rule['path'], $routeData);
                 }
             }
         }, ['cacheFile' => self::$CACHE_DIRECTORY . '/route.cache', 'cacheDisabled' => self::get('config')['debug']]);
     });
 }