diff --git a/docs/router.md b/docs/router.md index 7d88c8e..d2adfab 100644 --- a/docs/router.md +++ b/docs/router.md @@ -345,9 +345,9 @@ $router->setConfig([ ```php // 所有的默认的配置 -[ + // 是否忽略最后的 '/' 分隔符. 如果是 true,将清除最后一个 '/', 此时请求 '/home' 和 '/home/' 效果相同 - 'ignoreLastSep' => false, + 'ignoreLastSep' = false, // 匹配所有请求 // 1. 如果是一个有效的URI路径,将匹配所有请求到此URI路径。 @@ -360,7 +360,7 @@ $router->setConfig([ 'controllerNamespace' => '', // eg: 'app\\controllers' // 控制器类后缀 'controllerSuffix' => '', // eg: 'Controller' -] + ``` > NOTICE: 必须在添加路由之前调用 `$router->setConfig()` diff --git a/examples/cached.php b/examples/cached.php index e61b959..066df59 100644 --- a/examples/cached.php +++ b/examples/cached.php @@ -18,7 +18,7 @@ require __DIR__ . '/simple-loader.php'; $router = new CachedRouter([ - // 'ignoreLastSep' => true, + // 'ignoreLastSlash' => true, // 'tmpCacheNumber' => 100, // 'cacheFile' => '', diff --git a/examples/object.php b/examples/object.php index c19a4bd..66831fd 100644 --- a/examples/object.php +++ b/examples/object.php @@ -21,7 +21,7 @@ // set config $router->setConfig([ - // 'ignoreLastSep' => true, + // 'ignoreLastSlash' => true, // 'tmpCacheNumber' => 100, // 'matchAll' => '/', // a route path diff --git a/examples/static.php b/examples/static.php index fe3be2c..e039f19 100644 --- a/examples/static.php +++ b/examples/static.php @@ -18,7 +18,7 @@ // set config SRouter::setConfig([ - 'ignoreLastSep' => true, + 'ignoreLastSlash' => true, // 'matchAll' => '/', // a route path // 'matchAll' => function () { diff --git a/examples/swoole_svr.php b/examples/swoole_svr.php index a0f0c9a..0a36736 100644 --- a/examples/swoole_svr.php +++ b/examples/swoole_svr.php @@ -20,7 +20,7 @@ // set config $router->setConfig([ - 'ignoreLastSep' => true, + 'ignoreLastSlash' => true, 'dynamicAction' => true, 'tmpCacheNumber' => 100, diff --git a/src/AbstractRouter.php b/src/AbstractRouter.php index d00f74d..93c4362 100644 --- a/src/AbstractRouter.php +++ b/src/AbstractRouter.php @@ -11,7 +11,6 @@ /** * Class AbstractRouter * @package Inhere\Route - * * @method get(string $route, mixed $handler, array $opts = []) * @method post(string $route, mixed $handler, array $opts = []) * @method put(string $route, mixed $handler, array $opts = []) @@ -35,7 +34,7 @@ abstract class AbstractRouter implements RouterInterface 'any' => '[^/]+', // match any except '/' 'num' => '[0-9]+', // match a number 'int' => '\d+', // match a number - 'id' => '[1-9][0-9]*', // match a ID number + 'id' => '[1-9][0-9]*', // match a ID number 'act' => '[a-zA-Z][\w-]+', // match a action name ]; @@ -48,45 +47,13 @@ abstract class AbstractRouter implements RouterInterface /** @var array */ protected $currentGroupOption; - /** - * some setting for self - * @var array - */ - protected $config = [ - // the routes php file. - 'routesFile' => '', - - // ignore last '/' char. If is True, will clear last '/'. - 'ignoreLastSep' => false, - - // 'tmpCacheNumber' => 100, - 'tmpCacheNumber' => 0, - - // notAllowed As NotFound. Now, only two status value will be return(FOUND, NOT_FOUND). - 'notAllowedAsNotFound' => false, - - // match all request. - // 1. If is a valid URI path, will matchAll all request uri to the path. - // 2. If is a closure, will matchAll all request then call it - // eg: '/site/maintenance' or `function () { echo 'System Maintaining ... ...'; }` - 'matchAll' => false, - - // auto route match @like yii framework - // If is True, will auto find the handler controller file. - 'autoRoute' => false, - // The default controllers namespace, is valid when `'enable' = true` - 'controllerNamespace' => '', // eg: 'app\\controllers' - // controller suffix, is valid when `'enable' = true` - 'controllerSuffix' => '', // eg: 'Controller' - ]; - /** * static Routes - no dynamic argument match * 整个路由 path 都是静态字符串 e.g. '/user/login' * @var array[] * [ * '/user/login' => [ - * // METHOD => [...] // 这里 key 和 value里的 'methods' 是一样的 + * // METHOD => [...] * 'GET' => [ * 'handler' => 'handler', * 'option' => [...], @@ -109,16 +76,6 @@ abstract class AbstractRouter implements RouterInterface * @var array[] * [ * // 使用完整的第一节作为key进行分组 - * 'a' => [ - * [ - * 'start' => '/a/', - * 'regex' => '/a/(\w+)', - * 'methods' => 'GET,POST', - * 'handler' => 'handler', - * 'option' => [...], - * ], - * ... - * ], * 'add' => [ * [ * 'start' => '/add/', @@ -182,6 +139,61 @@ abstract class AbstractRouter implements RouterInterface */ protected $routeCaches = []; + /******************************************************************************* + * router config + ******************************************************************************/ + + /** + * Setting a routes file. + * @var string + */ + public $routesFile; + + /** + * Ignore last slash char('/'). If is True, will clear last '/'. + * @var bool + */ + public $ignoreLastSlash = false; + + /** + * The param route cache number. + * @var int + */ + public $tmpCacheNumber = 0; + + /** + * Match all request. + * 1. If is a valid URI path, will matchAll all request uri to the path. + * 2. If is a closure, will matchAll all request then call it + * eg: '/site/maintenance' or `function () { echo 'System Maintaining ... ...'; }` + * @var mixed + */ + public $matchAll; + + /** + * @var bool NotAllowed As NotFound. If True, only two status value will be return(FOUND, NOT_FOUND). + */ + public $notAllowedAsNotFound = false; + + /** + * Auto route match @like yii framework + * If is True, will auto find the handler controller file. + * @var bool + */ + public $autoRoute = false; + + /** + * The default controllers namespace. eg: 'App\\Controllers' + * @var string + */ + public $controllerNamespace; + + /** + * Controller suffix, is valid when '$autoRoute' = true. eg: 'Controller' + * @var string + */ + public $controllerSuffix; + /** * object creator. * @param array $config @@ -206,7 +218,7 @@ public function __construct(array $config = []) $this->currentGroupOption = []; // load routes - if (($file = $this->config['routesFile']) && is_file($file)) { + if (($file = $this->routesFile) && is_file($file)) { require $file; } } @@ -221,9 +233,20 @@ public function setConfig(array $config) throw new \LogicException('Routing has been added, and configuration is not allowed!'); } + $props = [ + 'routesFile' => 1, + 'ignoreLastSlash' => 1, + 'tmpCacheNumber' => 1, + 'notAllowedAsNotFound' => 1, + 'matchAll' => 1, + 'autoRoute' => 1, + 'controllerNamespace' => 1, + 'controllerSuffix' => 1, + ]; + foreach ($config as $name => $value) { - if (isset($this->config[$name])) { - $this->config[$name] = $value; + if (isset($props[$name])) { + $this->$name = $value; } } } @@ -289,7 +312,7 @@ public static function validateArguments($methods, $handler) } $allow = implode(',', self::SUPPORTED_METHODS) . ','; - $methods = array_map(function ($m) use($allow) { + $methods = array_map(function ($m) use ($allow) { $m = strtoupper(trim($m)); if (!$m || false === strpos($allow, $m . ',')) { @@ -349,16 +372,16 @@ protected function getFirstFromPath($path) /** * @param string $path - * @param bool $ignoreLastSep + * @param bool $ignoreLastSlash * @return string */ - protected function formatUriPath($path, $ignoreLastSep) + protected function formatUriPath($path, $ignoreLastSlash) { // clear '//', '///' => '/' $path = rawurldecode(preg_replace('#\/\/+#', '/', $path)); - // setting 'ignoreLastSep' - if ($path !== '/' && $ignoreLastSep) { + // setting 'ignoreLastSlash' + if ($path !== '/' && $ignoreLastSlash) { $path = rtrim($path, '/'); } @@ -370,7 +393,7 @@ protected function formatUriPath($path, $ignoreLastSep) * @param array $conf * @return array */ - protected static function filterMatches(array $matches, array $conf) + protected function filterMatches(array $matches, array $conf) { // clear all int key $matches = array_filter($matches, '\is_string', ARRAY_FILTER_USE_KEY); @@ -444,7 +467,7 @@ public function parseParamRoute($route, array $params, array $conf) $first = null; $regex = '#^' . $route . '$#'; $info = [ - 'regex' => $regex, + 'regex' => $regex, 'original' => $bak, ]; @@ -507,8 +530,11 @@ abstract protected function cacheMatchedParamRoute($path, $method, array $conf); */ public function matchAutoRoute($path) { - $cnp = trim($this->config['controllerNamespace']); - $sfx = trim($this->config['controllerSuffix']); + if (!$cnp = trim($this->controllerNamespace)) { + return false; + } + + $sfx = trim($this->controllerSuffix); $tmp = trim($path, '/- '); // one node. eg: 'home' @@ -616,20 +642,6 @@ public function addGlobalParam($name, $pattern) self::$globalParams[$name] = $pattern; } - /** - * @param null|string $name - * @param null|mixed $default - * @return array|string - */ - public function getConfig($name = null, $default = null) - { - if ($name) { - return isset($this->config[$name]) ? $this->config[$name] : $default; - } - - return $this->config; - } - /** * @return array */ diff --git a/src/CachedRouter.php b/src/CachedRouter.php index bb85c47..c055590 100644 --- a/src/CachedRouter.php +++ b/src/CachedRouter.php @@ -22,6 +22,18 @@ class CachedRouter extends ORouter /** @var bool */ private $cacheLoaded = false; + /** + * The routes cache file. + * @var string + */ + public $cacheFile; + + /** + * Enable routes cache + * @var bool + */ + public $cacheEnable = true; + /** * object constructor. * @param array $config @@ -29,11 +41,6 @@ class CachedRouter extends ORouter */ public function __construct(array $config = []) { - $this->config = array_merge($this->config,[ - 'cacheFile' => '', - 'cacheEnable' => true, - ]); - parent::__construct($config); // read route caches from cache file @@ -89,7 +96,7 @@ public function loadRoutesCache() return false; } - $file = $this->config['cacheFile']; + $file = $this->cacheFile; if (!$file || !file_exists($file)) { return false; @@ -112,7 +119,7 @@ public function loadRoutesCache() */ public function dumpRoutesCache() { - if (!$file = $this->config['cacheFile']) { + if (!$file = $this->cacheFile) { return false; } @@ -153,7 +160,7 @@ public function dumpRoutesCache() */ public function isCacheEnabled() { - return (bool)$this->getConfig('cacheEnable'); + return (bool)$this->cacheEnable; } /** @@ -161,7 +168,7 @@ public function isCacheEnabled() */ public function isCacheExists() { - return ($file = $this->config['cacheFile']) && file_exists($file); + return ($file = $this->cacheFile) && file_exists($file); } /** diff --git a/src/ORouter.php b/src/ORouter.php index d97ab47..07c928b 100644 --- a/src/ORouter.php +++ b/src/ORouter.php @@ -68,8 +68,8 @@ public function map($methods, $route, $handler, array $opts = []) $route = $this->currentGroupPrefix . $route; - // setting 'ignoreLastSep' - if ($route !== '/' && $this->config['ignoreLastSep']) { + // setting 'ignoreLastSlash' + if ($route !== '/' && $this->ignoreLastSlash) { $route = rtrim($route, '/'); } @@ -216,7 +216,7 @@ public function ctrl($prefix, $controllerClass, array $map = [], array $opts = [ public function match($path, $method = 'GET') { // if enable 'matchAll' - if ($matchAll = $this->config['matchAll']) { + if ($matchAll = $this->matchAll) { if (\is_string($matchAll) && $matchAll{0} === '/') { $path = $matchAll; } elseif (\is_callable($matchAll)) { @@ -227,7 +227,7 @@ public function match($path, $method = 'GET') } } - $path = $this->formatUriPath($path, $this->config['ignoreLastSep']); + $path = $this->formatUriPath($path, $this->ignoreLastSlash); $method = strtoupper($method); // find in route caches. @@ -267,7 +267,7 @@ public function match($path, $method = 'GET') } // handle Auto Route - if ($this->config['autoRoute'] && ($handler = $this->matchAutoRoute($path))) { + if ($this->autoRoute && ($handler = $this->matchAutoRoute($path))) { return [self::FOUND, $path, [ 'handler' => $handler, 'option' => [], @@ -306,7 +306,7 @@ public function match($path, $method = 'GET') return [self::FOUND, $path, $this->staticRoutes['/*'][$method]]; } - if ($this->config['notAllowedAsNotFound']) { + if ($this->notAllowedAsNotFound) { return [self::NOT_FOUND, $path, null]; } @@ -358,7 +358,7 @@ protected function findInRegularRoutes(array $routesData, $path, $method) $allowedMethods .= $conf['methods'] . ','; if (false !== strpos($conf['methods'] . ',', $method . ',')) { - $conf['matches'] = self::filterMatches($matches, $conf); + $conf['matches'] = $this->filterMatches($matches, $conf); $this->cacheMatchedParamRoute($path, $method, $conf); @@ -384,7 +384,7 @@ protected function findInVagueRoutes(array $routesData, $path, $method) } if (preg_match($conf['regex'], $path, $matches)) { - $conf['matches'] = self::filterMatches($matches, $conf); + $conf['matches'] = $this->filterMatches($matches, $conf); $this->cacheMatchedParamRoute($path, $method, $conf); @@ -402,7 +402,7 @@ protected function findInVagueRoutes(array $routesData, $path, $method) */ protected function cacheMatchedParamRoute($path, $method, array $conf) { - $cacheNumber = (int)$this->config['tmpCacheNumber']; + $cacheNumber = (int)$this->tmpCacheNumber; // cache last $cacheNumber routes. if ($cacheNumber > 0 && !isset($this->routeCaches[$path][$method])) {