This commit is contained in:
Your Name
2026-03-01 14:17:59 +08:00
parent 65aa12f146
commit a07e844c47
6071 changed files with 777651 additions and 0 deletions
@@ -0,0 +1,226 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace think\route;
use Psr\Http\Message\ResponseInterface;
use think\App;
use think\Container;
use think\Request;
use think\Response;
use think\Validate;
/**
* 路由调度基础类
*/
abstract class Dispatch
{
/**
* 应用对象
* @var App
*/
protected $app;
public function __construct(protected Request $request, protected Rule $rule, protected $dispatch, protected array $param = [])
{
}
public function init(App $app)
{
$this->app = $app;
// 执行路由后置操作
$this->doRouteAfter();
}
/**
* 执行路由调度
* @access public
* @return Response
*/
public function run(): Response
{
$data = $this->exec();
return $this->autoResponse($data);
}
protected function autoResponse($data): Response
{
if ($data instanceof Response) {
$response = $data;
} elseif ($data instanceof ResponseInterface) {
$response = Response::create((string) $data->getBody(), 'html', $data->getStatusCode());
foreach ($data->getHeaders() as $header => $values) {
$response->header([$header => implode(", ", $values)]);
}
} elseif (!is_null($data)) {
// 默认自动识别响应输出类型
$type = $this->request->isJson() ? 'json' : 'html';
$response = Response::create($data, $type);
} else {
$data = ob_get_clean();
$content = false === $data ? '' : $data;
$status = '' === $content && $this->request->isJson() ? 204 : 200;
$response = Response::create($content, 'html', $status);
}
return $response;
}
/**
* 检查路由后置操作
* @access protected
* @return void
*/
protected function doRouteAfter(): void
{
$option = $this->rule->getOption();
// 添加中间件
if (!empty($option['middleware'])) {
$this->app->middleware->import($option['middleware'], 'route');
}
if (!empty($option['append'])) {
$this->param = array_merge($this->param, $option['append']);
}
// 绑定模型数据
if (!empty($option['model'])) {
$this->createBindModel($option['model'], $this->param);
}
// 记录当前请求的路由规则
$this->request->setRule($this->rule);
// 记录路由变量
$this->request->setRoute($this->param);
// 数据自动验证
if (isset($option['validate'])) {
$this->autoValidate($option['validate']);
}
}
/**
* 路由绑定模型实例
* @access protected
* @param array $bindModel 绑定模型
* @param array $matches 路由变量
* @return void
*/
protected function createBindModel(array $bindModel, array $matches): void
{
foreach ($bindModel as $key => $val) {
if ($val instanceof \Closure) {
$result = $this->app->invokeFunction($val, $matches);
} else {
$fields = explode('&', $key);
if (is_array($val)) {
[$model, $exception] = $val;
} else {
$model = $val;
$exception = true;
}
$where = [];
$match = true;
foreach ($fields as $field) {
if (!isset($matches[$field])) {
$match = false;
break;
} else {
$where[] = [$field, '=', $matches[$field]];
}
}
if ($match) {
$result = $model::where($where)->failException($exception)->find();
}
}
if (!empty($result)) {
// 注入容器
$this->app->instance($result::class, $result);
}
}
}
/**
* 验证数据
* @access protected
* @param array $option
* @return void
* @throws \think\exception\ValidateException
*/
protected function autoValidate(array $option): void
{
[$validate, $scene, $message, $batch] = $option;
if (is_array($validate)) {
// 指定验证规则
$v = new Validate();
$v->rule($validate);
} else {
// 调用验证器
$class = str_contains($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
$v = new $class();
if (!empty($scene)) {
$v->scene($scene);
}
}
/** @var Validate $v */
$v->message($message)
->batch($batch)
->failException(true)
->check($this->request->param());
}
public function getDispatch()
{
return $this->dispatch;
}
public function getParam(): array
{
return $this->param;
}
abstract public function exec();
public function __sleep()
{
return ['rule', 'dispatch', 'param', 'controller', 'actionName'];
}
public function __wakeup()
{
$this->app = Container::pull('app');
$this->request = $this->app->request;
}
public function __debugInfo()
{
return [
'dispatch' => $this->dispatch,
'param' => $this->param,
'rule' => $this->rule,
];
}
}
@@ -0,0 +1,187 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace think\route;
use think\helper\Str;
use think\Request;
use think\Route;
use think\route\dispatch\Callback as CallbackDispatch;
use think\route\dispatch\Controller as ControllerDispatch;
/**
* 域名路由
*/
class Domain extends RuleGroup
{
/**
* 架构函数
* @access public
* @param Route $router 路由对象
* @param string $name 路由域名
* @param mixed $rule 域名路由
* @param bool $lazy 延迟解析
*/
public function __construct(Route $router, string $name = null, $rule = null, bool $lazy = false)
{
$this->router = $router;
$this->domain = $name;
$this->rule = $rule;
if (!$lazy && !is_null($rule)) {
$this->parseGroupRule($rule);
}
}
/**
* 检测域名路由
* @access public
* @param Request $request 请求对象
* @param string $url 访问地址
* @param bool $completeMatch 路由是否完全匹配
* @return Dispatch|false
*/
public function check(Request $request, string $url, bool $completeMatch = false)
{
// 检测URL绑定
$result = $this->checkUrlBind($request, $url);
if (!empty($this->option['append'])) {
$request->setRoute($this->option['append']);
unset($this->option['append']);
}
if (false !== $result) {
return $result;
}
return parent::check($request, $url, $completeMatch);
}
/**
* 设置路由绑定
* @access public
* @param string $bind 绑定信息
* @return $this
*/
public function bind(string $bind)
{
$this->router->bind($bind, $this->domain);
return $this;
}
/**
* 检测URL绑定
* @access private
* @param Request $request
* @param string $url URL地址
* @return Dispatch|false
*/
private function checkUrlBind(Request $request, string $url)
{
$bind = $this->router->getDomainBind($this->domain);
if ($bind) {
$this->parseBindAppendParam($bind);
// 如果有URL绑定 则进行绑定检测
$type = substr($bind, 0, 1);
$bind = substr($bind, 1);
$bindTo = [
'\\' => 'bindToClass',
'@' => 'bindToController',
':' => 'bindToNamespace',
];
if (isset($bindTo[$type])) {
return $this->{$bindTo[$type]}($request, $url, $bind);
}
}
return false;
}
protected function parseBindAppendParam(string &$bind): void
{
if (str_contains($bind, '?')) {
[$bind, $query] = explode('?', $bind);
parse_str($query, $vars);
$this->append($vars);
}
}
/**
* 绑定到类
* @access protected
* @param Request $request
* @param string $url URL地址
* @param string $class 类名(带命名空间)
* @return CallbackDispatch
*/
protected function bindToClass(Request $request, string $url, string $class): CallbackDispatch
{
$array = explode('|', $url, 2);
$action = !empty($array[0]) ? $array[0] : $this->config('default_action');
$param = [];
if (!empty($array[1])) {
$this->parseUrlParams($array[1], $param);
}
return new CallbackDispatch($request, $this, [$class, $action], $param);
}
/**
* 绑定到命名空间
* @access protected
* @param Request $request
* @param string $url URL地址
* @param string $namespace 命名空间
* @return CallbackDispatch
*/
protected function bindToNamespace(Request $request, string $url, string $namespace): CallbackDispatch
{
$array = explode('|', $url, 3);
$class = !empty($array[0]) ? $array[0] : $this->config('default_controller');
$method = !empty($array[1]) ? $array[1] : $this->config('default_action');
$param = [];
if (!empty($array[2])) {
$this->parseUrlParams($array[2], $param);
}
return new CallbackDispatch($request, $this, [$namespace . '\\' . Str::studly($class), $method], $param);
}
/**
* 绑定到控制器
* @access protected
* @param Request $request
* @param string $url URL地址
* @param string $controller 控制器名
* @return ControllerDispatch
*/
protected function bindToController(Request $request, string $url, string $controller): ControllerDispatch
{
$array = explode('|', $url, 2);
$action = !empty($array[0]) ? $array[0] : $this->config('default_action');
$param = [];
if (!empty($array[1])) {
$this->parseUrlParams($array[1], $param);
}
return new ControllerDispatch($request, $this, $controller . '/' . $action, $param);
}
}
@@ -0,0 +1,235 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace think\route;
use think\Route;
/**
* 资源路由类
*/
class Resource extends RuleGroup
{
/**
* REST方法定义
* @var array
*/
protected $rest = [];
/**
* 模型绑定
* @var array
*/
protected $model = [];
/**
* 数据验证
* @var array
*/
protected $validate = [];
/**
* 中间件
* @var array
*/
protected $middleware = [];
/**
* 架构函数
* @access public
* @param Route $router 路由对象
* @param RuleGroup $parent 上级对象
* @param string $name 资源名称
* @param string $route 路由地址
* @param array $rest 资源定义
*/
public function __construct(Route $router, RuleGroup $parent = null, string $name = '', string $route = '', array $rest = [])
{
$name = ltrim($name, '/');
$this->router = $router;
$this->parent = $parent;
$this->rule = $name;
$this->route = $route;
$this->name = str_contains($name, '.') ? strstr($name, '.', true) : $name;
$this->setFullName();
// 资源路由默认为完整匹配
$this->option['complete_match'] = true;
$this->rest = $rest;
if ($this->parent) {
$this->domain = $this->parent->getDomain();
$this->parent->addRuleItem($this);
}
}
/**
* 生成资源路由规则
* @access public
* @param mixed $rule 路由规则
* @return void
*/
public function parseGroupRule($rule): void
{
$option = $this->option;
$origin = $this->router->getGroup();
$this->router->setGroup($this);
if (str_contains($rule, '.')) {
// 注册嵌套资源路由
$array = explode('.', $rule);
$last = array_pop($array);
$item = [];
foreach ($array as $val) {
$item[] = $val . '/<' . ($option['var'][$val] ?? $val . '_id') . '>';
}
$rule = implode('/', $item) . '/' . $last;
}
$prefix = substr($rule, strlen($this->name) + 1);
// 注册资源路由
foreach ($this->rest as $key => $val) {
if ((isset($option['only']) && !in_array($key, $option['only']))
|| (isset($option['except']) && in_array($key, $option['except']))
) {
continue;
}
if (isset($last) && str_contains($val[1], '<id>') && isset($option['var'][$last])) {
$val[1] = str_replace('<id>', '<' . $option['var'][$last] . '>', $val[1]);
} elseif (str_contains($val[1], '<id>') && isset($option['var'][$rule])) {
$val[1] = str_replace('<id>', '<' . $option['var'][$rule] . '>', $val[1]);
}
$ruleItem = $this->addRule(trim($prefix . $val[1], '/'), $this->route . '/' . $val[2], $val[0]);
foreach (['model', 'validate', 'middleware', 'pattern'] as $name) {
if (isset($this->$name[$key])) {
call_user_func_array([$ruleItem, $name], (array) $this->$name[$key]);
}
}
}
$this->router->setGroup($origin);
$this->hasParsed = true;
}
/**
* 设置资源允许
* @access public
* @param array $only 资源允许
* @return $this
*/
public function only(array $only)
{
return $this->setOption('only', $only);
}
/**
* 设置资源排除
* @access public
* @param array $except 排除资源
* @return $this
*/
public function except(array $except)
{
return $this->setOption('except', $except);
}
/**
* 设置资源路由的变量
* @access public
* @param array $vars 资源变量
* @return $this
*/
public function vars(array $vars)
{
return $this->setOption('var', $vars);
}
/**
* 绑定资源验证
* @access public
* @param array|string $name 资源类型或者验证信息
* @param array|string $validate 验证信息
* @return $this
*/
public function withValidate(array|string $name, array|string $validate = [])
{
if (is_array($name)) {
$this->validate = array_merge($this->validate, $name);
} else {
$this->validate[$name] = $validate;
}
return $this;
}
/**
* 绑定资源模型
* @access public
* @param array|string $name 资源类型或者模型绑定
* @param array|string $model 模型绑定
* @return $this
*/
public function withModel(array|string $name, array|string $model = [])
{
if (is_array($name)) {
$this->model = array_merge($this->model, $name);
} else {
$this->model[$name] = $model;
}
return $this;
}
/**
* 绑定资源中间件
* @access public
* @param array|string $name 资源类型或者中间件定义
* @param array|string $middleware 中间件定义
* @return $this
*/
public function withMiddleware(array|string $name, array|string $middleware = [])
{
if (is_array($name)) {
$this->middleware = array_merge($this->middleware, $name);
} else {
$this->middleware[$name] = $middleware;
}
return $this;
}
/**
* rest方法定义和修改
* @access public
* @param array|string $name 方法名称
* @param array|bool $resource 资源
* @return $this
*/
public function rest(array|string $name, array|bool $resource = [])
{
if (is_array($name)) {
$this->rest = $resource ? $name : array_merge($this->rest, $name);
} else {
$this->rest[$name] = $resource;
}
return $this;
}
}
@@ -0,0 +1,72 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2021 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace think\route;
/**
* 资源路由注册类
*/
class ResourceRegister
{
/**
* 资源路由
* @var Resource
*/
protected $resource;
/**
* 是否注册过
* @var bool
*/
protected $registered = false;
/**
* 架构函数
* @access public
* @param Resource $resource 资源路由
*/
public function __construct(Resource $resource)
{
$this->resource = $resource;
}
/**
* 注册资源路由
* @access protected
* @return void
*/
protected function register()
{
$this->registered = true;
$this->resource->parseGroupRule($this->resource->getRule());
}
/**
* 动态方法
* @access public
* @param string $method 方法名
* @param array $args 调用参数
* @return mixed
*/
public function __call($method, $args)
{
return call_user_func_array([$this->resource, $method], $args);
}
public function __destruct()
{
if (!$this->registered) {
$this->register();
}
}
}
@@ -0,0 +1,928 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace think\route;
use Closure;
use think\Container;
use think\middleware\AllowCrossDomain;
use think\middleware\CheckRequestCache;
use think\middleware\FormTokenCheck;
use think\Request;
use think\Route;
use think\route\dispatch\Callback as CallbackDispatch;
use think\route\dispatch\Controller as ControllerDispatch;
/**
* 路由规则基础类
*/
abstract class Rule
{
/**
* 路由标识
* @var string
*/
protected $name;
/**
* 所在域名
* @var string
*/
protected $domain;
/**
* 路由对象
* @var Route
*/
protected $router;
/**
* 路由所属分组
* @var RuleGroup
*/
protected $parent;
/**
* 路由规则
* @var mixed
*/
protected $rule;
/**
* 路由地址
* @var string|Closure
*/
protected $route;
/**
* 请求类型
* @var string
*/
protected $method = '*';
/**
* 路由变量
* @var array
*/
protected $vars = [];
/**
* 路由参数
* @var array
*/
protected $option = [];
/**
* 路由变量规则
* @var array
*/
protected $pattern = [];
/**
* 需要和分组合并的路由参数
* @var array
*/
protected $mergeOptions = ['model', 'append', 'middleware'];
abstract public function check(Request $request, string $url, bool $completeMatch = false);
/**
* 设置路由参数
* @access public
* @param array $option 参数
* @return $this
*/
public function option(array $option)
{
$this->option = array_merge($this->option, $option);
return $this;
}
/**
* 设置单个路由参数
* @access public
* @param string $name 参数名
* @param mixed $value 值
* @return $this
*/
public function setOption(string $name, $value)
{
$this->option[$name] = $value;
return $this;
}
/**
* 注册变量规则
* @access public
* @param array $pattern 变量规则
* @return $this
*/
public function pattern(array $pattern)
{
$this->pattern = array_merge($this->pattern, $pattern);
return $this;
}
/**
* 设置标识
* @access public
* @param string $name 标识名
* @return $this
*/
public function name(string $name)
{
$this->name = $name;
return $this;
}
/**
* 获取路由对象
* @access public
* @return Route
*/
public function getRouter(): Route
{
return $this->router;
}
/**
* 获取Name
* @access public
* @return string
*/
public function getName(): string
{
return $this->name ?: '';
}
/**
* 获取当前路由规则
* @access public
* @return mixed
*/
public function getRule()
{
return $this->rule;
}
/**
* 获取当前路由地址
* @access public
* @return mixed
*/
public function getRoute()
{
return $this->route;
}
/**
* 获取当前路由的变量
* @access public
* @return array
*/
public function getVars(): array
{
return $this->vars;
}
/**
* 获取Parent对象
* @access public
* @return $this|null
*/
public function getParent()
{
return $this->parent;
}
/**
* 获取路由所在域名
* @access public
* @return string
*/
public function getDomain(): string
{
return $this->domain ?: $this->parent->getDomain();
}
/**
* 获取路由参数
* @access public
* @param string $name 变量名
* @return mixed
*/
public function config(string $name = '')
{
return $this->router->config($name);
}
/**
* 获取变量规则定义
* @access public
* @param string $name 变量名
* @return mixed
*/
public function getPattern(string $name = '')
{
$pattern = $this->pattern;
if ($this->parent) {
$pattern = array_merge($this->parent->getPattern(), $pattern);
}
if ('' === $name) {
return $pattern;
}
return $pattern[$name] ?? null;
}
/**
* 获取路由参数定义
* @access public
* @param string $name 参数名
* @param mixed $default 默认值
* @return mixed
*/
public function getOption(string $name = '', $default = null)
{
$option = $this->option;
if ($this->parent) {
$parentOption = $this->parent->getOption();
// 合并分组参数
foreach ($this->mergeOptions as $item) {
if (isset($parentOption[$item]) && isset($option[$item])) {
$option[$item] = array_merge($parentOption[$item], $option[$item]);
}
}
$option = array_merge($parentOption, $option);
}
if ('' === $name) {
return $option;
}
return $option[$name] ?? $default;
}
/**
* 获取当前路由的请求类型
* @access public
* @return string
*/
public function getMethod(): string
{
return strtolower($this->method);
}
/**
* 设置路由请求类型
* @access public
* @param string $method 请求类型
* @return $this
*/
public function method(string $method)
{
return $this->setOption('method', strtolower($method));
}
/**
* 检查后缀
* @access public
* @param string $ext URL后缀
* @return $this
*/
public function ext(string $ext = '')
{
return $this->setOption('ext', $ext);
}
/**
* 检查禁止后缀
* @access public
* @param string $ext URL后缀
* @return $this
*/
public function denyExt(string $ext = '')
{
return $this->setOption('deny_ext', $ext);
}
/**
* 检查域名
* @access public
* @param string $domain 域名
* @return $this
*/
public function domain(string $domain)
{
$this->domain = $domain;
return $this->setOption('domain', $domain);
}
/**
* 是否区分大小写
* @access public
* @param bool $case 是否区分
* @return $this
*/
public function caseUrl(bool $case)
{
return $this->setOption('case_sensitive', $case);
}
/**
* 设置参数过滤检查
* @access public
* @param array $filter 参数过滤
* @return $this
*/
public function filter(array $filter)
{
$this->option['filter'] = $filter;
return $this;
}
/**
* 绑定模型
* @access public
* @param array|string|Closure $var 路由变量名 多个使用 & 分割
* @param string|Closure $model 绑定模型类
* @param bool $exception 是否抛出异常
* @return $this
*/
public function model(array | string | Closure $var, string | Closure $model = null, bool $exception = true)
{
if ($var instanceof Closure) {
$this->option['model'][] = $var;
} elseif (is_array($var)) {
$this->option['model'] = $var;
} elseif (is_null($model)) {
$this->option['model']['id'] = [$var, true];
} else {
$this->option['model'][$var] = [$model, $exception];
}
return $this;
}
/**
* 附加路由隐式参数
* @access public
* @param array $append 追加参数
* @return $this
*/
public function append(array $append = [])
{
$this->option['append'] = $append;
return $this;
}
/**
* 绑定验证
* @access public
* @param mixed $validate 验证器类
* @param string $scene 验证场景
* @param array $message 验证提示
* @param bool $batch 批量验证
* @return $this
*/
public function validate($validate, string $scene = null, array $message = [], bool $batch = false)
{
$this->option['validate'] = [$validate, $scene, $message, $batch];
return $this;
}
/**
* 指定路由中间件
* @access public
* @param string|array|Closure $middleware 中间件
* @param mixed $params 参数
* @return $this
*/
public function middleware(string | array | Closure $middleware, ...$params)
{
if (empty($params) && is_array($middleware)) {
$this->option['middleware'] = $middleware;
} else {
foreach ((array) $middleware as $item) {
$this->option['middleware'][] = [$item, $params];
}
}
return $this;
}
/**
* 允许跨域
* @access public
* @param array $header 自定义Header
* @return $this
*/
public function allowCrossDomain(array $header = [])
{
return $this->middleware(AllowCrossDomain::class, $header);
}
/**
* 表单令牌验证
* @access public
* @param string $token 表单令牌token名称
* @return $this
*/
public function token(string $token = '__token__')
{
return $this->middleware(FormTokenCheck::class, $token);
}
/**
* 设置路由缓存
* @access public
* @param array|string|int $cache 缓存
* @return $this
*/
public function cache(array | string | int $cache)
{
return $this->middleware(CheckRequestCache::class, $cache);
}
/**
* 检查URL分隔符
* @access public
* @param string $depr URL分隔符
* @return $this
*/
public function depr(string $depr)
{
return $this->setOption('param_depr', $depr);
}
/**
* 设置需要合并的路由参数
* @access public
* @param array $option 路由参数
* @return $this
*/
public function mergeOptions(array $option = [])
{
$this->mergeOptions = array_merge($this->mergeOptions, $option);
return $this;
}
/**
* 检查是否为HTTPS请求
* @access public
* @param bool $https 是否为HTTPS
* @return $this
*/
public function https(bool $https = true)
{
return $this->setOption('https', $https);
}
/**
* 检查是否为JSON请求
* @access public
* @param bool $json 是否为JSON
* @return $this
*/
public function json(bool $json = true)
{
return $this->setOption('json', $json);
}
/**
* 检查是否为AJAX请求
* @access public
* @param bool $ajax 是否为AJAX
* @return $this
*/
public function ajax(bool $ajax = true)
{
return $this->setOption('ajax', $ajax);
}
/**
* 检查是否为PJAX请求
* @access public
* @param bool $pjax 是否为PJAX
* @return $this
*/
public function pjax(bool $pjax = true)
{
return $this->setOption('pjax', $pjax);
}
/**
* 路由到一个模板地址 需要额外传入的模板变量
* @access public
* @param array $view 视图
* @return $this
*/
public function view(array $view = [])
{
return $this->setOption('view', $view);
}
/**
* 通过闭包检查路由是否匹配
* @access public
* @param callable $match 闭包
* @return $this
*/
public function match(callable $match)
{
return $this->setOption('match', $match);
}
/**
* 设置路由完整匹配
* @access public
* @param bool $match 是否完整匹配
* @return $this
*/
public function completeMatch(bool $match = true)
{
return $this->setOption('complete_match', $match);
}
/**
* 是否去除URL最后的斜线
* @access public
* @param bool $remove 是否去除最后斜线
* @return $this
*/
public function removeSlash(bool $remove = true)
{
return $this->setOption('remove_slash', $remove);
}
/**
* 设置路由规则全局有效
* @access public
* @return $this
*/
public function crossDomainRule()
{
$this->router->setCrossDomainRule($this);
return $this;
}
/**
* 解析匹配到的规则路由
* @access public
* @param Request $request 请求对象
* @param string $rule 路由规则
* @param mixed $route 路由地址
* @param string $url URL地址
* @param array $option 路由参数
* @param array $matches 匹配的变量
* @return Dispatch
*/
public function parseRule(Request $request, string $rule, $route, string $url, array $option = [], array $matches = []): Dispatch
{
if (is_string($route) && isset($option['prefix'])) {
// 路由地址前缀
$route = $option['prefix'] . $route;
}
// 替换路由地址中的变量
$extraParams = true;
$search = $replace = [];
$depr = $this->config('pathinfo_depr');
foreach ($matches as $key => $value) {
$search[] = '<' . $key . '>';
$replace[] = $value;
$search[] = ':' . $key;
$replace[] = $value;
if (str_contains($value, $depr)) {
$extraParams = false;
}
}
if (is_string($route)) {
$route = str_replace($search, $replace, $route);
}
// 解析额外参数
if ($extraParams) {
$count = substr_count($rule, '/');
$url = array_slice(explode('|', $url), $count + 1);
$this->parseUrlParams(implode('|', $url), $matches);
}
$this->vars = $matches;
// 发起路由调度
return $this->dispatch($request, $route, $option);
}
/**
* 发起路由调度
* @access protected
* @param Request $request Request对象
* @param mixed $route 路由地址
* @param array $option 路由参数
* @return Dispatch
*/
protected function dispatch(Request $request, $route, array $option): Dispatch
{
if (is_subclass_of($route, Dispatch::class)) {
$result = new $route($request, $this, $route, $this->vars);
} elseif ($route instanceof Closure) {
// 执行闭包
$result = new CallbackDispatch($request, $this, $route, $this->vars);
} elseif (str_contains($route, '@') || str_contains($route, '::') || str_contains($route, '\\')) {
// 路由到类的方法
$route = str_replace('::', '@', $route);
$result = $this->dispatchMethod($request, $route);
} else {
// 路由到控制器/操作
$result = $this->dispatchController($request, $route);
}
return $result;
}
/**
* 解析URL地址为 模块/控制器/操作
* @access protected
* @param Request $request Request对象
* @param string $route 路由地址
* @return CallbackDispatch
*/
protected function dispatchMethod(Request $request, string $route): CallbackDispatch
{
$path = $this->parseUrlPath($route);
$route = str_replace('/', '@', implode('/', $path));
$method = str_contains($route, '@') ? explode('@', $route) : $route;
return new CallbackDispatch($request, $this, $method, $this->vars);
}
/**
* 解析URL地址为 模块/控制器/操作
* @access protected
* @param Request $request Request对象
* @param string $route 路由地址
* @return ControllerDispatch
*/
protected function dispatchController(Request $request, string $route): ControllerDispatch
{
$path = $this->parseUrlPath($route);
$action = array_pop($path);
$controller = !empty($path) ? array_pop($path) : null;
// 路由到模块/控制器/操作
return new ControllerDispatch($request, $this, [$controller, $action], $this->vars);
}
/**
* 路由检查
* @access protected
* @param array $option 路由参数
* @param Request $request Request对象
* @return bool
*/
protected function checkOption(array $option, Request $request): bool
{
// 检查当前路由是否匹配
if (isset($option['match']) && is_callable($option['match'])) {
if (false === $option['match']($this, $request)) {
return false;
}
}
// 请求类型检测
if (!empty($option['method'])) {
if (is_string($option['method']) && false === stripos($option['method'], $request->method())) {
return false;
}
}
// AJAX PJAX 请求检查
foreach (['ajax', 'pjax', 'json'] as $item) {
if (isset($option[$item])) {
$call = 'is' . $item;
if ($option[$item] && !$request->$call() || !$option[$item] && $request->$call()) {
return false;
}
}
}
// 伪静态后缀检测
if ($request->url() != '/' && ((isset($option['ext']) && false === stripos('|' . $option['ext'] . '|', '|' . $request->ext() . '|'))
|| (isset($option['deny_ext']) && false !== stripos('|' . $option['deny_ext'] . '|', '|' . $request->ext() . '|')))) {
return false;
}
// 域名检查
if ((isset($option['domain']) && !in_array($option['domain'], [$request->host(true), $request->subDomain()]))) {
return false;
}
// HTTPS检查
if ((isset($option['https']) && $option['https'] && !$request->isSsl())
|| (isset($option['https']) && !$option['https'] && $request->isSsl())
) {
return false;
}
// 请求参数检查
if (isset($option['filter'])) {
foreach ($option['filter'] as $name => $value) {
if ($request->param($name, '') != $value) {
return false;
}
}
}
return true;
}
/**
* 解析URL地址中的参数Request对象
* @access protected
* @param string $rule 路由规则
* @param array $var 变量
* @return void
*/
protected function parseUrlParams(string $url, array &$var = []): void
{
if ($url) {
preg_replace_callback('/(\w+)\|([^\|]+)/', function ($match) use (&$var) {
$var[$match[1]] = strip_tags($match[2]);
}, $url);
}
}
/**
* 解析URL的pathinfo参数
* @access public
* @param string $url URL地址
* @return array
*/
public function parseUrlPath(string $url): array
{
// 分隔符替换 确保路由定义使用统一的分隔符
$url = str_replace('|', '/', $url);
$url = trim($url, '/');
if (str_contains($url, '/')) {
// [控制器/操作]
$path = explode('/', $url);
} else {
$path = [$url];
}
return $path;
}
/**
* 生成路由的正则规则
* @access protected
* @param string $rule 路由规则
* @param array $match 匹配的变量
* @param array $pattern 路由变量规则
* @param array $option 路由参数
* @param bool $completeMatch 路由是否完全匹配
* @param string $suffix 路由正则变量后缀
* @return string
*/
protected function buildRuleRegex(string $rule, array $match, array $pattern = [], array $option = [], bool $completeMatch = false, string $suffix = ''): string
{
foreach ($match as $name) {
$value = $this->buildNameRegex($name, $pattern, $suffix);
if ($value) {
$origin[] = $name;
$replace[] = $value;
}
}
// 是否区分 / 地址访问
if ('/' != $rule) {
if (!empty($option['remove_slash'])) {
$rule = rtrim($rule, '/');
} elseif (str_ends_with($rule, '/')) {
$rule = rtrim($rule, '/');
$hasSlash = true;
}
}
$regex = isset($replace) ? str_replace($origin, $replace, $rule) : $rule;
$regex = str_replace([')?/', ')?-'], [')/', ')-'], $regex);
if (isset($hasSlash)) {
$regex .= '/';
}
return $regex . ($completeMatch ? '$' : '');
}
/**
* 生成路由变量的正则规则
* @access protected
* @param string $name 路由变量
* @param array $pattern 变量规则
* @param string $suffix 路由正则变量后缀
* @return string
*/
protected function buildNameRegex(string $name, array $pattern, string $suffix): string
{
$optional = '';
$slash = substr($name, 0, 1);
if (in_array($slash, ['/', '-'])) {
$prefix = $slash;
$name = substr($name, 1);
$slash = substr($name, 0, 1);
} else {
$prefix = '';
}
if ('<' != $slash) {
return '';
}
if (str_contains($name, '?')) {
$name = substr($name, 1, -2);
$optional = '?';
} elseif (str_contains($name, '>')) {
$name = substr($name, 1, -1);
}
if (isset($pattern[$name])) {
$nameRule = $pattern[$name];
if (str_starts_with($nameRule, '/') && str_ends_with($nameRule, '/')) {
$nameRule = substr($nameRule, 1, -1);
}
} else {
$nameRule = $this->config('default_route_pattern');
}
return '(' . $prefix . '(?<' . $name . $suffix . '>' . $nameRule . '))' . $optional;
}
/**
* 设置路由参数
* @access public
* @param string $method 方法名
* @param array $args 调用参数
* @return $this
*/
public function __call($method, $args)
{
if (count($args) > 1) {
$args[0] = $args;
}
array_unshift($args, $method);
return call_user_func_array([$this, 'setOption'], $args);
}
public function __sleep()
{
return ['name', 'rule', 'route', 'method', 'vars', 'option', 'pattern'];
}
public function __wakeup()
{
$this->router = Container::pull('route');
}
public function __debugInfo()
{
return [
'name' => $this->name,
'rule' => $this->rule,
'route' => $this->route,
'method' => $this->method,
'vars' => $this->vars,
'option' => $this->option,
'pattern' => $this->pattern,
];
}
}
@@ -0,0 +1,504 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace think\route;
use Closure;
use think\Container;
use think\Exception;
use think\Request;
use think\Route;
/**
* 路由分组类
*/
class RuleGroup extends Rule
{
/**
* 分组路由(包括子分组)
* @var Rule[]
*/
protected $rules = [];
/**
* MISS路由
* @var RuleItem
*/
protected $miss;
/**
* 完整名称
* @var string
*/
protected $fullName;
/**
* 分组别名
* @var string
*/
protected $alias;
/**
* 是否已经解析
* @var bool
*/
protected $hasParsed;
/**
* 架构函数
* @access public
* @param Route $router 路由对象
* @param RuleGroup $parent 上级对象
* @param string $name 分组名称
* @param mixed $rule 分组路由
* @param bool $lazy 延迟解析
*/
public function __construct(Route $router, RuleGroup $parent = null, string $name = '', $rule = null, bool $lazy = false)
{
$this->router = $router;
$this->parent = $parent;
$this->rule = $rule;
$this->name = trim($name, '/');
$this->setFullName();
if ($this->parent) {
$this->domain = $this->parent->getDomain();
$this->parent->addRuleItem($this);
}
if (!$lazy) {
$this->parseGroupRule($rule);
}
}
/**
* 设置分组的路由规则
* @access public
* @return void
*/
protected function setFullName(): void
{
if (str_contains($this->name, ':')) {
$this->name = preg_replace(['/\[\:(\w+)\]/', '/\:(\w+)/'], ['<\1?>', '<\1>'], $this->name);
}
if ($this->parent && $this->parent->getFullName()) {
$this->fullName = $this->parent->getFullName() . ($this->name ? '/' . $this->name : '');
} else {
$this->fullName = $this->name;
}
if ($this->name) {
$this->router->getRuleName()->setGroup($this->name, $this);
}
}
/**
* 获取所属域名
* @access public
* @return string
*/
public function getDomain(): string
{
return $this->domain ?: '-';
}
/**
* 获取分组别名
* @access public
* @return string
*/
public function getAlias(): string
{
return $this->alias ?: '';
}
/**
* 检测分组路由
* @access public
* @param Request $request 请求对象
* @param string $url 访问地址
* @param bool $completeMatch 路由是否完全匹配
* @return Dispatch|false
*/
public function check(Request $request, string $url, bool $completeMatch = false)
{
// 检查分组有效性
if (!$this->checkOption($this->option, $request) || !$this->checkUrl($url)) {
return false;
}
// 解析分组路由
if (!$this->hasParsed) {
$this->parseGroupRule($this->rule);
}
// 获取当前路由规则
$method = strtolower($request->method());
$rules = $this->getRules($method);
$option = $this->getOption();
if (isset($option['complete_match'])) {
$completeMatch = $option['complete_match'];
}
if (!empty($option['merge_rule_regex'])) {
// 合并路由正则规则进行路由匹配检查
$result = $this->checkMergeRuleRegex($request, $rules, $url, $completeMatch);
if (false !== $result) {
return $result;
}
}
// 检查分组路由
foreach ($rules as $item) {
$result = $item->check($request, $url, $completeMatch);
if (false !== $result) {
return $result;
}
}
if (!empty($option['dispatcher'])) {
$result = $this->parseRule($request, '', $option['dispatcher'], $url, $option);
} elseif ($miss = $this->getMissRule($method)) {
// 未匹配所有路由的路由规则处理
$result = $miss->parseRule($request, '', $miss->getRoute(), $url, $miss->getOption());
} else {
$result = false;
}
return $result;
}
/**
* 分组URL匹配检查
* @access protected
* @param string $url URL
* @return bool
*/
protected function checkUrl(string $url): bool
{
if ($this->fullName) {
$pos = strpos($this->fullName, '<');
if (false !== $pos) {
$str = substr($this->fullName, 0, $pos);
} else {
$str = $this->fullName;
}
if ($str && 0 !== stripos(str_replace('|', '/', $url), $str)) {
return false;
}
}
return true;
}
/**
* 设置路由分组别名
* @access public
* @param string $alias 路由分组别名
* @return $this
*/
public function alias(string $alias)
{
$this->alias = $alias;
$this->router->getRuleName()->setGroup($alias, $this);
return $this;
}
/**
* 解析分组和域名的路由规则及绑定
* @access public
* @param mixed $rule 路由规则
* @return void
*/
public function parseGroupRule($rule): void
{
if (is_string($rule) && is_subclass_of($rule, Dispatch::class)) {
$this->dispatcher($rule);
return;
}
$origin = $this->router->getGroup();
$this->router->setGroup($this);
if ($rule instanceof Closure) {
Container::getInstance()->invokeFunction($rule);
} elseif (is_string($rule) && $rule) {
$this->router->bind($rule, $this->domain);
}
$this->router->setGroup($origin);
$this->hasParsed = true;
}
/**
* 检测分组路由
* @access public
* @param Request $request 请求对象
* @param array $rules 路由规则
* @param string $url 访问地址
* @param bool $completeMatch 路由是否完全匹配
* @return Dispatch|false
*/
protected function checkMergeRuleRegex(Request $request, array &$rules, string $url, bool $completeMatch)
{
$depr = $this->config('pathinfo_depr');
$url = $depr . str_replace('|', $depr, $url);
$regex = [];
$items = [];
foreach ($rules as $key => $item) {
if ($item instanceof RuleItem) {
$rule = $depr . str_replace('/', $depr, $item->getRule());
if ($depr == $rule && $depr != $url) {
unset($rules[$key]);
continue;
}
$complete = $item->getOption('complete_match', $completeMatch);
if (!str_contains($rule, '<')) {
if (0 === strcasecmp($rule, $url) || (!$complete && 0 === strncasecmp($rule, $url, strlen($rule)))) {
return $item->checkRule($request, $url, []);
}
unset($rules[$key]);
continue;
}
$slash = preg_quote('/-' . $depr, '/');
if ($matchRule = preg_split('/[' . $slash . ']<\w+\??>/', $rule, 2)) {
if ($matchRule[0] && 0 !== strncasecmp($rule, $url, strlen($matchRule[0]))) {
unset($rules[$key]);
continue;
}
}
if (preg_match_all('/[' . $slash . ']?<?\w+\??>?/', $rule, $matches)) {
unset($rules[$key]);
$pattern = array_merge($this->getPattern(), $item->getPattern());
$option = array_merge($this->getOption(), $item->getOption());
$regex[$key] = $this->buildRuleRegex($rule, $matches[0], $pattern, $option, $complete, '_THINK_' . $key);
$items[$key] = $item;
}
}
}
if (empty($regex)) {
return false;
}
try {
$result = preg_match('~^(?:' . implode('|', $regex) . ')~u', $url, $match);
} catch (\Exception $e) {
throw new Exception('route pattern error');
}
if ($result) {
$var = [];
foreach ($match as $key => $val) {
if (is_string($key) && '' !== $val) {
[$name, $pos] = explode('_THINK_', $key);
$var[$name] = $val;
}
}
if (!isset($pos)) {
foreach ($regex as $key => $item) {
if (str_starts_with(str_replace(['\/', '\-', '\\' . $depr], ['/', '-', $depr], $item), $match[0])) {
$pos = $key;
break;
}
}
}
$rule = $items[$pos]->getRule();
$array = $this->router->getRule($rule);
foreach ($array as $item) {
if (in_array($item->getMethod(), ['*', strtolower($request->method())])) {
$result = $item->checkRule($request, $url, $var);
if (false !== $result) {
return $result;
}
}
}
}
return false;
}
/**
* 注册MISS路由
* @access public
* @param string|Closure $route 路由地址
* @param string $method 请求类型
* @return RuleItem
*/
public function miss(string|Closure $route, string $method = '*'): RuleItem
{
// 创建路由规则实例
$method = strtolower($method);
$ruleItem = new RuleItem($this->router, $this, null, '', $route, $method);
$this->miss[$method] = $ruleItem->setMiss();
return $ruleItem;
}
/**
* 添加分组下的MISS路由
* @access public
* @param string $method 请求类型
* @return RuleItem|null
*/
public function getMissRule(string $method = '*'): ?RuleItem
{
if (isset($this->miss[$method])) {
$miss = $this->miss[$method];
} elseif (isset($this->miss['*'])) {
$miss = $this->miss['*'];
} else {
return null;
}
return $miss;
}
/**
* 添加分组下的路由规则
* @access public
* @param string $rule 路由规则
* @param mixed $route 路由地址
* @param string $method 请求类型
* @return RuleItem
*/
public function addRule(string $rule, $route = null, string $method = '*'): RuleItem
{
// 读取路由标识
if (is_string($route)) {
$name = $route;
} else {
$name = null;
}
$method = strtolower($method);
if ('' === $rule || '/' === $rule) {
$rule .= '$';
}
// 创建路由规则实例
$ruleItem = new RuleItem($this->router, $this, $name, $rule, $route, $method);
$this->addRuleItem($ruleItem);
return $ruleItem;
}
/**
* 注册分组下的路由规则
* @access public
* @param Rule $rule 路由规则
* @return $this
*/
public function addRuleItem(Rule $rule)
{
$this->rules[] = $rule;
return $this;
}
/**
* 设置分组的路由前缀
* @access public
* @param string $prefix 路由前缀
* @return $this
*/
public function prefix(string $prefix)
{
if ($this->parent && $this->parent->getOption('prefix')) {
$prefix = $this->parent->getOption('prefix') . $prefix;
}
return $this->setOption('prefix', $prefix);
}
/**
* 合并分组的路由规则正则
* @access public
* @param bool $merge 是否合并
* @return $this
*/
public function mergeRuleRegex(bool $merge = true)
{
return $this->setOption('merge_rule_regex', $merge);
}
/**
* 设置分组的Dispatch调度
* @access public
* @param string $dispatch 调度类
* @return $this
*/
public function dispatcher(string $dispatch)
{
return $this->setOption('dispatcher', $dispatch);
}
/**
* 获取完整分组Name
* @access public
* @return string
*/
public function getFullName(): string
{
return $this->fullName ?: '';
}
/**
* 获取分组的路由规则
* @access public
* @param string $method 请求类型
* @return array
*/
public function getRules(string $method = ''): array
{
if ('' === $method) {
return $this->rules;
}
return array_filter($this->rules, function ($item) use ($method) {
$ruleMethod = $item->getMethod();
return '*' == $ruleMethod || str_contains($ruleMethod, $method);
});
}
/**
* 清空分组下的路由规则
* @access public
* @return void
*/
public function clear(): void
{
$this->rules = [];
}
}
@@ -0,0 +1,316 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace think\route;
use think\Exception;
use think\Request;
use think\Route;
/**
* 路由规则类
*/
class RuleItem extends Rule
{
/**
* 是否为MISS规则
* @var bool
*/
protected $miss = false;
/**
* 是否为额外自动注册的OPTIONS规则
* @var bool
*/
protected $autoOption = false;
/**
* 架构函数
* @access public
* @param Route $router 路由实例
* @param RuleGroup $parent 上级对象
* @param string $name 路由标识
* @param string $rule 路由规则
* @param string|\Closure $route 路由地址
* @param string $method 请求类型
*/
public function __construct(Route $router, RuleGroup $parent, string $name = null, string $rule = '', $route = null, string $method = '*')
{
$this->router = $router;
$this->parent = $parent;
$this->name = $name;
$this->route = $route;
$this->method = $method;
$this->setRule($rule);
$this->router->setRule($this->rule, $this);
}
/**
* 设置当前路由规则为MISS路由
* @access public
* @return $this
*/
public function setMiss()
{
$this->miss = true;
return $this;
}
/**
* 判断当前路由规则是否为MISS路由
* @access public
* @return bool
*/
public function isMiss(): bool
{
return $this->miss;
}
/**
* 获取当前路由的URL后缀
* @access public
* @return string|null
*/
public function getSuffix(): ?string
{
if (isset($this->option['ext'])) {
$suffix = $this->option['ext'];
} elseif ($this->parent->getOption('ext')) {
$suffix = $this->parent->getOption('ext');
} else {
$suffix = null;
}
return $suffix;
}
/**
* 路由规则预处理
* @access public
* @param string $rule 路由规则
* @return void
*/
public function setRule(string $rule): void
{
if (str_ends_with($rule, '$')) {
// 是否完整匹配
$rule = substr($rule, 0, -1);
$this->option['complete_match'] = true;
}
$rule = '/' != $rule ? ltrim($rule, '/') : '';
if ($this->parent && $prefix = $this->parent->getFullName()) {
$rule = $prefix . ($rule ? '/' . ltrim($rule, '/') : '');
}
if (str_contains($rule, ':')) {
$this->rule = preg_replace(['/\[\:(\w+)\]/', '/\:(\w+)/'], ['<\1?>', '<\1>'], $rule);
} else {
$this->rule = $rule;
}
// 生成路由标识的快捷访问
$this->setRuleName();
}
/**
* 设置别名
* @access public
* @param string $name
* @return $this
*/
public function name(string $name)
{
$this->name = $name;
$this->setRuleName(true);
return $this;
}
/**
* 设置路由标识 用于URL反解生成
* @access protected
* @param bool $first 是否插入开头
* @return void
*/
protected function setRuleName(bool $first = false): void
{
if ($this->name) {
$this->router->setName($this->name, $this, $first);
}
}
/**
* 检测路由
* @access public
* @param Request $request 请求对象
* @param string $url 访问地址
* @param array $match 匹配路由变量
* @param bool $completeMatch 路由是否完全匹配
* @return Dispatch|false
*/
public function checkRule(Request $request, string $url, array $match = null, bool $completeMatch = false)
{
// 检查参数有效性
if (!$this->checkOption($this->option, $request)) {
return false;
}
// 合并分组参数
$option = $this->getOption();
$pattern = $this->getPattern();
$url = $this->urlSuffixCheck($request, $url, $option);
if (is_null($match)) {
$match = $this->checkMatch($url, $option, $pattern, $completeMatch);
}
if (false !== $match) {
return $this->parseRule($request, $this->rule, $this->route, $url, $option, $match);
}
return false;
}
/**
* 检测路由(含路由匹配)
* @access public
* @param Request $request 请求对象
* @param string $url 访问地址
* @param bool $completeMatch 路由是否完全匹配
* @return Dispatch|false
*/
public function check(Request $request, string $url, bool $completeMatch = false)
{
return $this->checkRule($request, $url, null, $completeMatch);
}
/**
* URL后缀及Slash检查
* @access protected
* @param Request $request 请求对象
* @param string $url 访问地址
* @param array $option 路由参数
* @return string
*/
protected function urlSuffixCheck(Request $request, string $url, array $option = []): string
{
// 是否区分 / 地址访问
if (!empty($option['remove_slash']) && '/' != $this->rule) {
$this->rule = rtrim($this->rule, '/');
$url = rtrim($url, '|');
}
if (isset($option['ext'])) {
// 路由ext参数 优先于系统配置的URL伪静态后缀参数
$url = preg_replace('/\.(' . $request->ext() . ')$/i', '', $url);
}
return $url;
}
/**
* 检测URL和规则路由是否匹配
* @access private
* @param string $url URL地址
* @param array $option 路由参数
* @param array $pattern 变量规则
* @param bool $completeMatch 是否完全匹配
* @return array|false
*/
private function checkMatch(string $url, array $option, array $pattern, bool $completeMatch)
{
if (isset($option['complete_match'])) {
$completeMatch = $option['complete_match'];
}
$depr = $this->config('pathinfo_depr');
if (isset($option['case_sensitive'])) {
$case = $option['case_sensitive'];
} else {
$case = $this->config('url_case_sensitive');
}
// 检查完整规则定义
if (isset($pattern['__url__']) && !preg_match(str_starts_with($pattern['__url__'], '/') ? $pattern['__url__'] : '/^' . $pattern['__url__'] . ($completeMatch ? '$' : '') . '/', str_replace('|', $depr, $url))) {
return false;
}
$var = [];
$url = $depr . str_replace('|', $depr, $url);
$rule = $depr . str_replace('/', $depr, $this->rule);
if ($depr == $rule && $depr != $url) {
return false;
}
if (!str_contains($rule, '<')) {
if ($case && (0 === strcmp($rule, $url) || (!$completeMatch && 0 === strncmp($rule . $depr, $url . $depr, strlen($rule . $depr))))) {
return $var;
} elseif (!$case && (0 === strcasecmp($rule, $url) || (!$completeMatch && 0 === strncasecmp($rule . $depr, $url . $depr, strlen($rule . $depr))))) {
return $var;
}
return false;
}
$slash = preg_quote('/-' . $depr, '/');
if ($matchRule = preg_split('/[' . $slash . ']?<\w+\??>/', $rule, 2)) {
if ($matchRule[0] && 0 !== strncasecmp($rule, $url, strlen($matchRule[0]))) {
return false;
}
}
if (preg_match_all('/[' . $slash . ']?<?\w+\??>?/', $rule, $matches)) {
$regex = $this->buildRuleRegex($rule, $matches[0], $pattern, $option, $completeMatch);
try {
if (!preg_match('~^' . $regex . '~u' . ($case ? '' : 'i'), $url, $match)) {
return false;
}
} catch (\Exception $e) {
throw new Exception('route pattern error');
}
foreach ($match as $key => $val) {
if (is_string($key)) {
$var[$key] = $val;
}
}
}
// 成功匹配后返回URL中的动态变量数组
return $var;
}
/**
* 设置路由所属分组(用于注解路由)
* @access public
* @param string $name 分组名称或者标识
* @return $this
*/
public function group(string $name)
{
$group = $this->router->getRuleName()->getGroup($name);
if ($group) {
$this->parent = $group;
$this->setRule($this->rule);
}
return $this;
}
}
@@ -0,0 +1,211 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace think\route;
/**
* 路由标识管理类
*/
class RuleName
{
/**
* 路由标识
* @var array
*/
protected $item = [];
/**
* 路由规则
* @var array
*/
protected $rule = [];
/**
* 路由分组
* @var array
*/
protected $group = [];
/**
* 注册路由标识
* @access public
* @param string $name 路由标识
* @param RuleItem $ruleItem 路由规则
* @param bool $first 是否优先
* @return void
*/
public function setName(string $name, RuleItem $ruleItem, bool $first = false): void
{
$name = strtolower($name);
$item = $this->getRuleItemInfo($ruleItem);
if ($first && isset($this->item[$name])) {
array_unshift($this->item[$name], $item);
} else {
$this->item[$name][] = $item;
}
}
/**
* 注册路由分组标识
* @access public
* @param string $name 路由分组标识
* @param RuleGroup $group 路由分组
* @return void
*/
public function setGroup(string $name, RuleGroup $group): void
{
$this->group[strtolower($name)] = $group;
}
/**
* 注册路由规则
* @access public
* @param string $rule 路由规则
* @param RuleItem $ruleItem 路由
* @return void
*/
public function setRule(string $rule, RuleItem $ruleItem): void
{
$route = $ruleItem->getRoute();
if (is_string($route)) {
$this->rule[$rule][$route] = $ruleItem;
} else {
$this->rule[$rule][] = $ruleItem;
}
}
/**
* 根据路由规则获取路由对象(列表)
* @access public
* @param string $rule 路由标识
* @return RuleItem[]
*/
public function getRule(string $rule): array
{
return $this->rule[$rule] ?? [];
}
/**
* 根据路由分组标识获取分组
* @access public
* @param string $name 路由分组标识
* @return RuleGroup|null
*/
public function getGroup(string $name): ?RuleGroup
{
return $this->group[strtolower($name)] ?? null;
}
/**
* 清空路由规则
* @access public
* @return void
*/
public function clear(): void
{
$this->item = [];
$this->rule = [];
}
/**
* 获取全部路由列表
* @access public
* @return array
*/
public function getRuleList(): array
{
$list = [];
foreach ($this->rule as $rule => $rules) {
foreach ($rules as $item) {
$val = [];
foreach (['method', 'rule', 'name', 'route', 'domain', 'pattern', 'option'] as $param) {
$call = 'get' . $param;
$val[$param] = $item->$call();
}
if ($item->isMiss()) {
$val['rule'] .= '<MISS>';
}
$list[] = $val;
}
}
return $list;
}
/**
* 导入路由标识
* @access public
* @param array $item 路由标识
* @return void
*/
public function import(array $item): void
{
$this->item = $item;
}
/**
* 根据路由标识获取路由信息(用于URL生成)
* @access public
* @param string $name 路由标识
* @param string $domain 域名
* @param string $method 请求类型
* @return array
*/
public function getName(string $name = null, string $domain = null, string $method = '*'): array
{
if (is_null($name)) {
return $this->item;
}
$name = strtolower($name);
$method = strtolower($method);
$result = [];
if (isset($this->item[$name])) {
if (is_null($domain)) {
$result = $this->item[$name];
} else {
foreach ($this->item[$name] as $item) {
$itemDomain = $item['domain'];
$itemMethod = $item['method'];
if (($itemDomain == $domain || '-' == $itemDomain) && ('*' == $itemMethod || '*' == $method || $method == $itemMethod)) {
$result[] = $item;
}
}
}
}
return $result;
}
/**
* 获取路由信息
* @access protected
* @param RuleItem $item 路由规则
* @return array
*/
protected function getRuleItemInfo(RuleItem $item): array
{
return [
'rule' => $item->getRule(),
'domain' => $item->getDomain(),
'method' => $item->getMethod(),
'suffix' => $item->getSuffix(),
];
}
}
+491
View File
@@ -0,0 +1,491 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace think\route;
use think\App;
use think\Route;
/**
* 路由地址生成
*/
class Url
{
/**
* URL 根地址
* @var string
*/
protected $root = '';
/**
* HTTPS
* @var bool
*/
protected $https;
/**
* URL后缀
* @var string|bool
*/
protected $suffix = true;
/**
* URL域名
* @var string|bool
*/
protected $domain = false;
/**
* 架构函数
* @access public
* @param Route $route URL地址
* @param App $app App对象
* @param string $url URL地址
* @param array $vars 参数
*/
public function __construct(protected Route $route, protected App $app, protected string $url = '', protected array $vars = [])
{
}
/**
* 设置URL参数
* @access public
* @param array $vars URL参数
* @return $this
*/
public function vars(array $vars = [])
{
$this->vars = $vars;
return $this;
}
/**
* 设置URL后缀
* @access public
* @param string|bool $suffix URL后缀
* @return $this
*/
public function suffix(string|bool $suffix)
{
$this->suffix = $suffix;
return $this;
}
/**
* 设置URL域名(或者子域名)
* @access public
* @param string|bool $domain URL域名
* @return $this
*/
public function domain(string|bool $domain)
{
$this->domain = $domain;
return $this;
}
/**
* 设置URL 根地址
* @access public
* @param string $root URL root
* @return $this
*/
public function root(string $root)
{
$this->root = $root;
return $this;
}
/**
* 设置是否使用HTTPS
* @access public
* @param bool $https
* @return $this
*/
public function https(bool $https = true)
{
$this->https = $https;
return $this;
}
/**
* 检测域名
* @access protected
* @param string $url URL
* @param string|true $domain 域名
* @return string
*/
protected function parseDomain(string &$url, string|bool $domain): string
{
if (!$domain) {
return '';
}
$request = $this->app->request;
$rootDomain = $request->rootDomain();
if (true === $domain) {
// 自动判断域名
$domain = $request->host();
$domains = $this->route->getDomains();
if (!empty($domains)) {
$routeDomain = array_keys($domains);
foreach ($routeDomain as $domainPrefix) {
if (str_starts_with($domainPrefix, '*.') && str_contains($domain, ltrim($domainPrefix, '*.')) !== false) {
foreach ($domains as $key => $rule) {
$rule = is_array($rule) ? $rule[0] : $rule;
if (is_string($rule) && !str_contains($key, '*') && str_starts_with($url, $rule)) {
$url = ltrim($url, $rule);
$domain = $key;
// 生成对应子域名
if (!empty($rootDomain)) {
$domain .= $rootDomain;
}
break;
} elseif (str_contains($key, '*')) {
if (!empty($rootDomain)) {
$domain .= $rootDomain;
}
break;
}
}
}
}
}
} elseif (!str_contains($domain, '.') && !str_starts_with($domain, $rootDomain)) {
$domain .= '.' . $rootDomain;
}
if (str_contains($domain, '://')) {
$scheme = '';
} else {
$scheme = $this->https || $request->isSsl() ? 'https://' : 'http://';
}
return $scheme . $domain;
}
/**
* 解析URL后缀
* @access protected
* @param string|bool $suffix 后缀
* @return string
*/
protected function parseSuffix(string|bool $suffix): string
{
if ($suffix) {
$suffix = true === $suffix ? $this->route->config('url_html_suffix') : $suffix;
if (is_string($suffix) && $pos = strpos($suffix, '|')) {
$suffix = substr($suffix, 0, $pos);
}
}
return (empty($suffix) || str_starts_with($suffix, '.')) ? (string) $suffix : '.' . $suffix;
}
/**
* 直接解析URL地址
* @access protected
* @param string $url URL
* @param string|bool $domain Domain
* @return string
*/
protected function parseUrl(string $url, string | bool &$domain): string
{
$request = $this->app->request;
if (str_starts_with($url, '/')) {
// 直接作为路由地址解析
$url = substr($url, 1);
} elseif (str_contains($url, '\\')) {
// 解析到类
$url = ltrim(str_replace('\\', '/', $url), '/');
} elseif (str_starts_with($url, '@')) {
// 解析到控制器
$url = substr($url, 1);
} elseif ('' === $url) {
$url = $request->controller() . '/' . $request->action();
} else {
$controller = $request->controller();
$path = explode('/', $url);
$action = array_pop($path);
$controller = empty($path) ? $controller : array_pop($path);
$url = $controller . '/' . $action;
}
return $url;
}
/**
* 分析路由规则中的变量
* @access protected
* @param string $rule 路由规则
* @return array
*/
protected function parseVar(string $rule): array
{
// 提取路由规则中的变量
$var = [];
if (preg_match_all('/<\w+\??>/', $rule, $matches)) {
foreach ($matches[0] as $name) {
$optional = false;
if (str_contains($name, '?')) {
$name = substr($name, 1, -2);
$optional = true;
} else {
$name = substr($name, 1, -1);
}
$var[$name] = $optional ? 2 : 1;
}
}
return $var;
}
/**
* 匹配路由地址
* @access protected
* @param array $rule 路由规则
* @param array $vars 路由变量
* @param string|bool $allowDomain 允许域名
* @return array
*/
protected function getRuleUrl(array $rule, array &$vars = [], string|bool $allowDomain = ''): array
{
$request = $this->app->request;
if (is_string($allowDomain) && !str_contains($allowDomain, '.')) {
$allowDomain .= '.' . $request->rootDomain();
}
$port = $request->port();
foreach ($rule as $item) {
$url = $item['rule'];
$pattern = $this->parseVar($url);
$domain = $item['domain'];
$suffix = $item['suffix'];
if ('-' == $domain) {
$domain = is_string($allowDomain) ? $allowDomain : $request->host(true);
}
if (is_string($allowDomain) && $domain != $allowDomain) {
continue;
}
if ($port && !in_array($port, [80, 443])) {
$domain .= ':' . $port;
}
if (empty($pattern)) {
return [rtrim($url, '?-'), $domain, $suffix];
}
$type = $this->route->config('url_common_param');
$keys = [];
foreach ($pattern as $key => $val) {
if (isset($vars[$key])) {
$url = str_replace(['[:' . $key . ']', '<' . $key . '?>', ':' . $key, '<' . $key . '>'], $type ? (string) $vars[$key] : urlencode((string) $vars[$key]), $url);
$keys[] = $key;
$url = str_replace(['/?', '-?'], ['/', '-'], $url);
$result = [rtrim($url, '?-'), $domain, $suffix];
} elseif (2 == $val) {
$url = str_replace(['/[:' . $key . ']', '[:' . $key . ']', '<' . $key . '?>'], '', $url);
$url = str_replace(['/?', '-?'], ['/', '-'], $url);
$result = [rtrim($url, '?-'), $domain, $suffix];
} else {
$result = null;
$keys = [];
break;
}
}
$vars = array_diff_key($vars, array_flip($keys));
if (isset($result)) {
return $result;
}
}
return [];
}
/**
* 生成URL地址
* @access public
* @return string
*/
public function build(): string
{
// 解析URL
$url = $this->url;
$suffix = $this->suffix;
$domain = $this->domain;
$request = $this->app->request;
$vars = $this->vars;
if (str_starts_with($url, '[') && $pos = strpos($url, ']')) {
// [name] 表示使用路由命名标识生成URL
$name = substr($url, 1, $pos - 1);
$url = 'name' . substr($url, $pos + 1);
}
if (!str_contains($url, '://') && !str_starts_with($url, '/')) {
$info = parse_url($url);
$url = !empty($info['path']) ? $info['path'] : '';
if (isset($info['fragment'])) {
// 解析锚点
$anchor = $info['fragment'];
if (str_contains($anchor, '?')) {
// 解析参数
[$anchor, $info['query']] = explode('?', $anchor, 2);
}
if (str_contains($anchor, '@')) {
// 解析域名
[$anchor, $domain] = explode('@', $anchor, 2);
}
} elseif (str_contains($url, '@') && !str_contains($url, '\\')) {
// 解析域名
[$url, $domain] = explode('@', $url, 2);
}
}
if ($url) {
$checkName = isset($name) ? $name : $url . (isset($info['query']) ? '?' . $info['query'] : '');
$checkDomain = $domain && is_string($domain) ? $domain : null;
$rule = $this->route->getName($checkName, $checkDomain);
if (empty($rule) && isset($info['query'])) {
$rule = $this->route->getName($url, $checkDomain);
// 解析地址里面参数 合并到vars
parse_str($info['query'], $params);
$vars = array_merge($params, $vars);
unset($info['query']);
}
}
if (!empty($rule) && $match = $this->getRuleUrl($rule, $vars, $domain)) {
// 匹配路由命名标识
$url = $match[0];
if ($domain && !empty($match[1])) {
$domain = $match[1];
}
if (!is_null($match[2])) {
$suffix = $match[2];
}
} elseif (!empty($rule) && isset($name)) {
throw new \InvalidArgumentException('route name not exists:' . $name);
} else {
// 检测URL绑定
$bind = $this->route->getDomainBind($domain && is_string($domain) ? $domain : null);
if ($bind && str_starts_with($url, $bind)) {
$url = substr($url, strlen($bind) + 1);
} else {
$binds = $this->route->getBind();
foreach ($binds as $key => $val) {
if (is_string($val) && str_starts_with($url, $val) && substr_count($val, '/') > 1) {
$url = substr($url, strlen($val) + 1);
$domain = $key;
break;
}
}
}
// 路由标识不存在 直接解析
$url = $this->parseUrl($url, $domain);
if (isset($info['query'])) {
// 解析地址里面参数 合并到vars
parse_str($info['query'], $params);
$vars = array_merge($params, $vars);
}
}
// 还原URL分隔符
$depr = $this->route->config('pathinfo_depr');
$url = str_replace('/', $depr, $url);
$file = $request->baseFile();
if ($file && !str_starts_with($request->url(), $file)) {
$file = str_replace('\\', '/', dirname($file));
}
$url = rtrim($file, '/') . '/' . $url;
// URL后缀
if (str_ends_with($url, '/') || '' == $url) {
$suffix = '';
} else {
$suffix = $this->parseSuffix($suffix);
}
// 锚点
$anchor = !empty($anchor) ? '#' . $anchor : '';
// 参数组装
if (!empty($vars)) {
// 添加参数
if ($this->route->config('url_common_param')) {
$vars = http_build_query($vars);
$url .= $suffix . ($vars ? '?' . $vars : '') . $anchor;
} else {
foreach ($vars as $var => $val) {
$val = (string) $val;
if ('' !== $val) {
$url .= $depr . $var . $depr . urlencode($val);
}
}
$url .= $suffix . $anchor;
}
} else {
$url .= $suffix . $anchor;
}
// 检测域名
$domain = $this->parseDomain($url, $domain);
// URL组装
return $domain . rtrim($this->root, '/') . '/' . ltrim($url, '/');
}
public function __toString()
{
return $this->build();
}
public function __debugInfo()
{
return [
'url' => $this->url,
'vars' => $this->vars,
'suffix' => $this->suffix,
'domain' => $this->domain,
];
}
}
@@ -0,0 +1,29 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace think\route\dispatch;
use think\route\Dispatch;
/**
* Callback Dispatcher
*/
class Callback extends Dispatch
{
public function exec()
{
// 执行回调方法
$vars = array_merge($this->request->param(), $this->param);
return $this->app->invoke($this->dispatch, $vars);
}
}
@@ -0,0 +1,194 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace think\route\dispatch;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use think\App;
use think\exception\ClassNotFoundException;
use think\exception\HttpException;
use think\helper\Str;
use think\route\Dispatch;
/**
* Controller Dispatcher
*/
class Controller extends Dispatch
{
/**
* 控制器名
* @var string
*/
protected $controller;
/**
* 操作名
* @var string
*/
protected $actionName;
public function init(App $app)
{
parent::init($app);
$result = $this->dispatch;
if (is_string($result)) {
$result = explode('/', $result);
}
// 获取控制器名
$controller = strip_tags($result[0] ?: $this->rule->config('default_controller'));
if (str_contains($controller, '.')) {
$pos = strrpos($controller, '.');
$this->controller = substr($controller, 0, $pos) . '.' . Str::studly(substr($controller, $pos + 1));
} else {
$this->controller = Str::studly($controller);
}
// 获取操作名
$this->actionName = strip_tags($result[1] ?: $this->rule->config('default_action'));
// 设置当前请求的控制器、操作
$this->request
->setController($this->controller)
->setAction($this->actionName);
}
public function exec()
{
try {
// 实例化控制器
$instance = $this->controller($this->controller);
} catch (ClassNotFoundException $e) {
throw new HttpException(404, 'controller not exists:' . $e->getClass());
}
// 注册控制器中间件
$this->registerControllerMiddleware($instance);
return $this->app->middleware->pipeline('controller')
->send($this->request)
->then(function () use ($instance) {
// 获取当前操作名
$suffix = $this->rule->config('action_suffix');
$action = $this->actionName . $suffix;
if (is_callable([$instance, $action])) {
$vars = $this->request->param();
try {
$reflect = new ReflectionMethod($instance, $action);
// 严格获取当前操作方法名
$actionName = $reflect->getName();
if ($suffix) {
$actionName = substr($actionName, 0, -strlen($suffix));
}
$this->request->setAction($actionName);
} catch (ReflectionException $e) {
$reflect = new ReflectionMethod($instance, '__call');
$vars = [$action, $vars];
$this->request->setAction($action);
}
} else {
// 操作不存在
throw new HttpException(404, 'method not exists:' . $instance::class . '->' . $action . '()');
}
$data = $this->app->invokeReflectMethod($instance, $reflect, $vars);
return $this->autoResponse($data);
});
}
protected function parseActions($actions)
{
return array_map(function ($item) {
return strtolower($item);
}, is_string($actions) ? explode(",", $actions) : $actions);
}
/**
* 使用反射机制注册控制器中间件
* @access public
* @param object $controller 控制器实例
* @return void
*/
protected function registerControllerMiddleware($controller): void
{
$class = new ReflectionClass($controller);
if ($class->hasProperty('middleware')) {
$reflectionProperty = $class->getProperty('middleware');
$reflectionProperty->setAccessible(true);
$middlewares = $reflectionProperty->getValue($controller);
$action = $this->request->action(true);
foreach ($middlewares as $key => $val) {
if (!is_int($key)) {
$middleware = $key;
$options = $val;
} elseif (isset($val['middleware'])) {
$middleware = $val['middleware'];
$options = $val['options'] ?? [];
} else {
$middleware = $val;
$options = [];
}
if (isset($options['only']) && !in_array($action, $this->parseActions($options['only']))) {
continue;
} elseif (isset($options['except']) && in_array($action, $this->parseActions($options['except']))) {
continue;
}
if (is_string($middleware) && str_contains($middleware, ':')) {
$middleware = explode(':', $middleware);
if (count($middleware) > 1) {
$middleware = [$middleware[0], array_slice($middleware, 1)];
}
}
$this->app->middleware->controller($middleware);
}
}
}
/**
* 实例化访问控制器
* @access public
* @param string $name 资源地址
* @return object
* @throws ClassNotFoundException
*/
public function controller(string $name)
{
$suffix = $this->rule->config('controller_suffix') ? 'Controller' : '';
$controllerLayer = $this->rule->config('controller_layer') ?: 'controller';
$emptyController = $this->rule->config('empty_controller') ?: 'Error';
$class = $this->app->parseClass($controllerLayer, $name . $suffix);
if (class_exists($class)) {
return $this->app->make($class, [], true);
} elseif ($emptyController && class_exists($emptyClass = $this->app->parseClass($controllerLayer, $emptyController . $suffix))) {
return $this->app->make($emptyClass, [], true);
}
throw new ClassNotFoundException('class not exists:' . $class, $class);
}
}
@@ -0,0 +1,117 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace think\route\dispatch;
use think\exception\HttpException;
use think\helper\Str;
use think\Request;
use think\route\Rule;
/**
* Url Dispatcher
*/
class Url extends Controller
{
public function __construct(Request $request, Rule $rule, $dispatch)
{
$this->request = $request;
$this->rule = $rule;
// 解析默认的URL规则
$dispatch = $this->parseUrl($dispatch);
parent::__construct($request, $rule, $dispatch, $this->param);
}
/**
* 解析URL地址
* @access protected
* @param string $url URL
* @return array
*/
protected function parseUrl(string $url): array
{
$depr = $this->rule->config('pathinfo_depr');
$bind = $this->rule->getRouter()->getDomainBind();
if ($bind && preg_match('/^[a-z]/is', $bind)) {
$bind = str_replace('/', $depr, $bind);
// 如果有域名绑定
$url = $bind . (!str_ends_with($bind, '.') ? $depr : '') . ltrim($url, $depr);
}
$path = $this->rule->parseUrlPath($url);
if (empty($path)) {
return [null, null];
}
// 解析控制器
$controller = !empty($path) ? array_shift($path) : null;
if ($controller && !preg_match('/^[A-Za-z0-9][\w|\.]*$/', $controller)) {
throw new HttpException(404, 'controller not exists:' . $controller);
}
// 解析操作
$action = !empty($path) ? array_shift($path) : null;
$var = [];
// 解析额外参数
if ($path) {
preg_replace_callback('/(\w+)\|([^\|]+)/', function ($match) use (&$var) {
$var[$match[1]] = strip_tags($match[2]);
}, implode('|', $path));
}
$panDomain = $this->request->panDomain();
if ($panDomain && $key = array_search('*', $var)) {
// 泛域名赋值
$var[$key] = $panDomain;
}
// 设置当前请求的参数
$this->param = $var;
// 封装路由
$route = [$controller, $action];
if ($this->hasDefinedRoute($route)) {
throw new HttpException(404, 'invalid request:' . str_replace('|', $depr, $url));
}
return $route;
}
/**
* 检查URL是否已经定义过路由
* @access protected
* @param array $route 路由信息
* @return bool
*/
protected function hasDefinedRoute(array $route): bool
{
[$controller, $action] = $route;
// 检查地址是否被定义过路由
$name = strtolower(Str::studly($controller) . '/' . $action);
$host = $this->request->host(true);
$method = $this->request->method();
if ($this->rule->getRouter()->getName($name, $host, $method)) {
return true;
}
return false;
}
}