Laravel Route(路由)匹配源码分析
基于laravel10
分析
这里不分析是怎么走到路由的,只分析路由是怎么匹配的
直接看Illuminate\Routing\Router
类的findRoute
方法
这里是去查找对应的路由
看一下这个方法做了什么处理
$this->routes = new RouteCollection;
protected function findRoute($request)
{
$this->events->dispatch(new Routing($request));
//这里是去匹配路由
$this->current = $route = ①$this->routes->match($request);
$route->setContainer($this->container);
$this->container->instance(Route::class, $route);
return $route;
}
①看一下Illuminate\Routing\RouteCollection
类的match
方法做了什么处理
public function match(Request $request)
{
//前面的文章分析了路由是怎么注册的,每个请求方法都对应一个路由数组
//这里就是去获取当前请求对应的路由数组
$routes = $this->get($request->getMethod());
//这里是去看路由数组中是否存在匹配的路由
$route = ②$this->matchAgainstRoutes($routes, $request);
//这里是处理匹配到的路由 最后面再来分析这个
return $this->handleMatchedRoute($request, $route);
}
②看一下Illuminate\Routing\RouteCollection
类的matchAgainstRoutes
方法做了什么处理
protected function matchAgainstRoutes(array $routes, $request, $includingMethod = true)
{
//这里是把回退路由和普通理由分离
[$fallbacks, $routes] = collect($routes)->partition(function ($route) {
return $route->isFallback;
});
//把回退路由放到最后面去防止干扰路由匹配
return $routes->merge($fallbacks)->first(
fn (Route $route) => ③$route->matches($request, $includingMethod)
);
}
③看一下Illuminate\Routing\Route
类的matches
方法做了什么处理
public function matches(Request $request, $includingMethod = true)
{
//这里是重点
//编译路由
④$this->compileRoute();
//这里就是去匹配规则
foreach (self::getValidators() as $validator) {
//!$includingMethod 这个是用于没有在对应的请求方法中找到路由的时候 查找其他方式中是否存在 存在就抛出一个405的异常
if (! $includingMethod && $validator instanceof MethodValidator) {
continue;
}
//这里就是去调用对应类的matches方法 看是否能匹配
if (! $validator->matches($this, $request)) {
return false;
}
}
}
public static function getValidators()
{
if (isset(static::$validators)) {
return static::$validators;
}
return static::$validators = [
//验证路径
new UriValidator,
//验证方法
new MethodValidator,
//验证协议
new SchemeValidator,
//验证域名
new HostValidator,
];
}
④看一下Illuminate\Routing\Route
类的compileRoute
方法做了什么处理
protected function compileRoute()
{
if (! $this->compiled) {
//这里是交给了Symfony的路由组件去做处理了
$this->compiled = ⑤$this->toSymfonyRoute()->compile();
}
return $this->compiled;
}
④看一下Illuminate\Routing\Route
类的toSymfonyRoute
方法做了什么处理
use Symfony\Component\Routing\Route as SymfonyRoute;
public function toSymfonyRoute()
{
//这里是实例化Symfony的路由组件
return new ⑤SymfonyRoute(
//去掉参数可选(路径去掉参数问号)
preg_replace('/\{(\w+?)\?\}/', '{$1}', $this->uri()),
//获取可选参数
$this->getOptionalParameterNames(),
//正则表达式数组
$this->wheres,
//选项参数 固定传入这个
['utf8' => true],
//获取domain
$this->getDomain() ?: '',
//协议http/https
[],
//路由請求方法
$this->methods
);
}
protected function getOptionalParameterNames()
{
//匹配可选参数
preg_match_all('/\{(\w+?)\?\}/', $this->uri(), $matches);
//用参数名称为key 值填充null
return isset($matches[1]) ? array_fill_keys($matches[1], null) : [];
}
⑤看一下Symfony\Component\Routing\Route
类的__construct
构造函数做了什么处理
public function __construct(string $path, array $defaults = [], array $requirements = [], array $options = [], ?string $host = '', string|array $schemes = [], string|array $methods = [], ?string $condition = '')
{
$this->setPath($path);
$this->addDefaults($defaults);
$this->addRequirements($requirements);
$this->setOptions($options);
$this->setHost($host);
$this->setSchemes($schemes);
$this->setMethods($methods);
$this->setCondition($condition);
}
public function setPath(string $pattern): static
{
//这个在下面有说明
$pattern = $this->extractInlineDefaultsAndRequirements($pattern);
$this->path = '/'.ltrim(trim($pattern), '/');
$this->compiled = null;
return $this;
}
public function addDefaults(array $defaults): static
{
//这里先不用看 这个是Symfony 路由组件的特殊路由参数
if (isset($defaults['_locale']) && $this->isLocalized()) {
unset($defaults['_locale']);
}
foreach ($defaults as $name => $default) {
$this->defaults[$name] = $default;
}
$this->compiled = null;
return $this;
}
public function addRequirements(array $requirements): static
{
//这里先不用看 这个是Symfony 路由组件的特殊路由参数
if (isset($requirements['_locale']) && $this->isLocalized()) {
unset($requirements['_locale']);
}
foreach ($requirements as $key => $regex) {
$this->requirements[$key] = $this->sanitizeRequirement($key, $regex);
}
$this->compiled = null;
return $this;
}
public function setOptions(array $options): static
{
$this->options = [
'compiler_class' => \Symfony\Component\Routing\RouteCompiler::class,
];
return $this->addOptions($options);
}
public function setHost(?string $pattern): static
{
//这里和setPath方法中的方法相同 下面有说明
$this->host = $this->extractInlineDefaultsAndRequirements((string) $pattern);
$this->compiled = null;
return $this;
}
public function setSchemes(string|array $schemes): static
{
$this->schemes = array_map('strtolower', (array) $schemes);
$this->compiled = null;
return $this;
}
public function setMethods(string|array $methods): static
{
$this->methods = array_map('strtoupper', (array) $methods);
$this->compiled = null;
return $this;
}
public function setCondition(?string $condition): static
{
$this->condition = (string) $condition;
$this->compiled = null;
return $this;
}
private function extractInlineDefaultsAndRequirements(string $pattern): string
{
if (false === strpbrk($pattern, '?<')) {
return $pattern;
}
//这里是路由参数是否有默认值和正则验证
//例如 'a.b.{ccc<[a-z]+>?dasd}'
return preg_replace_callback('#\{(!?)([\w\x80-\xFF]++)(<.*?>)?(\?[^\}]*+)?\}#', function ($m) {
//以上面例子说明
//$m[4]是第四个捕获组中的值(这里是?dasd) (字符串可以用数组的方式去下标 就是对应的第几位字符)
if (isset($m[4][0])) {
//设置默认值 $m[2]就是第二个捕获组中的值(这里是ccc)
//如果只有问号 那默认值就是null 否则就是问号后面的值为默认值(这里是dasd)
$this->setDefault($m[2], '?' !== $m[4] ? substr($m[4], 1) : null);
}
///$m[3]是第三个捕获组中的值(这里是<[a-z]+>)
if (isset($m[3][0])) {
//设置正则验证
//substr($m[3], 1, -1) 这里就是过滤两边的"<>"得到里面的正则表达式
$this->setRequirement($m[2], substr($m[3], 1, -1));
}
return '{'.$m[1].$m[2].'}';
}, $pattern);
}
⑤初始化完Symfony路由组件后,会调用Symfony路由组件的compile
方法
看一下这个方法做了什么处理
public function compile(): CompiledRoute
{
if (null !== $this->compiled) {
return $this->compiled;
}
//这里就是拿setOption方法中设置的compiler_class
//对应Symfony\Component\Routing\RouteCompiler类
$class = $this->getOption('compiler_class');
return $this->compiled = ⑥$class::compile($this);
}
⑥看一下Symfony\Component\Routing\RouteCompiler
类的compile
方法做了什么处理
public static function compile(Route $route): CompiledRoute
{
$hostVariables = [];
$variables = [];
$hostRegex = null;
$hostTokens = [];
//是否设置了host(对应laravel中的domain)
if ('' !== $host = $route->getHost()) {
//编译匹配
$result = ⑦self::compilePattern($route, $host, true);
$hostVariables = $result['variables'];
$variables = $hostVariables;
$hostTokens = $result['tokens'];
$hostRegex = $result['regex'];
}
//这里是symfony路由组件的特殊路由参数 这里先不分析这个
$locale = $route->getDefault('_locale');
if (null !== $locale && null !== $route->getDefault('_canonical_route') && preg_quote($locale) === $route->getRequirement('_locale')) {
unset($requirements['_locale']);
$route->setRequirements($requirements);
$route->setPath(str_replace('{_locale}', $locale, $route->getPath()));
}
$path = $route->getPath();
//这里和host一样 也是编译匹配
$result = self::compilePattern($route, $path, false);
$staticPrefix = $result['staticPrefix'];
$pathVariables = $result['variables'];
foreach ($pathVariables as $pathParam) {
//这里也是symfony路由组件的特殊路由参数 这里先不分析这个
if ('_fragment' === $pathParam) {
throw new \InvalidArgumentException(sprintf('Route pattern "%s" cannot contain "_fragment" as a path parameter.', $route->getPath()));
}
}
$variables = array_merge($variables, $pathVariables);
$tokens = $result['tokens'];
$regex = $result['regex'];
return new CompiledRoute(
$staticPrefix,
$regex,
$tokens,
$pathVariables,
$hostRegex,
$hostTokens,
$hostVariables,
array_unique($variables)
);
}
⑦看一下Symfony\Component\Routing\RouteCompiler
类的compilePattern
方法做了什么处理
private static function compilePattern(Route $route, string $pattern, bool $isHost): array
{
$tokens = [];
$variables = [];
$matches = [];
$pos = 0;
//因为host和path都会来这里 如果是host 默认分隔符是"." 反之 默认分隔符是"/"
$defaultSeparator = $isHost ? '.' : '/';
//这里是验证host和path 是否是utf8编码字符
$useUtf8 = preg_match('//u', $pattern);
//这里是字符是否必须是utf8编码字符
$needsUtf8 = $route->getOption('utf8');
//英文字符的编码在\x01-\x79(1-127)之间,[\x80-\xff]表示非ASCII码字符,匹配中文字符
//如果字符不需要是utf8编码字符 且 使用了utf8字符 且是存在中文字符 就抛出异常
if (!$needsUtf8 && $useUtf8 && preg_match('/[\x80-\xFF]/', $pattern)) {
throw new \LogicException(sprintf('Cannot use UTF-8 route patterns without setting the "utf8" option for route "%s".', $route->getPath()));
}
//使用了不是utf8编码字符 且 字符是否必须是utf8编码字符 就抛出异常
if (!$useUtf8 && $needsUtf8) {
throw new \LogicException(sprintf('Cannot mix UTF-8 requirements with non-UTF-8 pattern "%s".', $pattern));
}
//这里是匹配路由参数
//\PREG_OFFSET_CAPTURE 匹配返回时会增加它相对目标字符串的字节偏移量
//\PREG_SET_ORDER 结果排序为$matches[0]包含第一次匹配得到的所有匹配(包含子组), $matches[1]是包含第二次匹配到的所有匹配(包含子组)的数组,以此类推。
preg_match_all('#\{(!)?([\w\x80-\xFF]+)\}#', $pattern, $matches, \PREG_OFFSET_CAPTURE | \PREG_SET_ORDER);
foreach ($matches as $match) {
//这里就是检测是否存在"!" 后面会说这个的作用
$important = $match[1][1] >= 0;
//拿到路由参数名
$varName = $match[2][0];
//这里是获取当前路由参数前的静态文本
//例如 /a/b.{num1}/c/{num2}
//静态文本就是/a/b. 和 /c/
$precedingText = substr($pattern, $pos, $match[0][1] - $pos);
//这里是把下标移到当前路由参数的最后一位字符后一位
$pos = $match[0][1] + \strlen($match[0][0]);
//如果前面的静态文本为空
if (!\strlen($precedingText)) {
//前面一位字符设置为空
$precedingChar = '';
} elseif ($useUtf8) {
//匹配当前静态文本的最后一位字符
preg_match('/.$/u', $precedingText, $precedingChar);
//获取到最后一位字符
$precedingChar = $precedingChar[0];
} else {
//获取到最后一位字符
$precedingChar = substr($precedingText, -1);
}
//是否为分隔符
//public const SEPARATORS = '/,;.:-_~+*=@|'; 这些字符都是分隔符
$isSeparator = '' !== $precedingChar && str_contains(static::SEPARATORS, $precedingChar);
//变量不能是以数字开头
if (preg_match('/^\d/', $varName)) {
throw new \DomainException(sprintf('Variable name "%s" cannot start with a digit in route pattern "%s". Please use a different name.', $varName, $pattern));
}
//路由参数名不能一样
if (\in_array($varName, $variables)) {
throw new \LogicException(sprintf('Route pattern "%s" cannot reference variable name "%s" more than once.', $pattern, $varName));
}
///路由参数名超过设定的最大长度
if (\strlen($varName) > self::VARIABLE_MAXIMUM_LENGTH) {
throw new \DomainException(sprintf('Variable name "%s" cannot be longer than %d characters in route pattern "%s". Please use a shorter name.', $varName, self::VARIABLE_MAXIMUM_LENGTH, $pattern));
}
//如果是分隔符 且 文本不等于分隔符 证明前面有静态文本
if ($isSeparator && $precedingText !== $precedingChar) {
//当前这个token就被标记为text 去掉最后的分隔符
$tokens[] = ['text', substr($precedingText, 0, -\strlen($precedingChar))];
}
//如果不是分隔符 且 静态文本不是空
elseif (!$isSeparator && '' !== $precedingText) {
//当前这个token就被标记为text 因为没有分隔符 所以不用去掉最后的分隔符
$tokens[] = ['text', $precedingText];
}
//获取路由参数的正则表达式
$regexp = $route->getRequirement($varName);
if (null === $regexp) {
//如果没有正则表达式 创建一个正则表达式
//这里是拿到当前路由参数的后面的字符串
$followingPattern = (string) substr($pattern, $pos);
//这里是拿到后一个分隔符 禁止用户输入这个符号
$nextSeparator = self::findNextSeparator($followingPattern, $useUtf8);
//这个正则表达式就是排除/和下一个分隔符
//例如 [^/@]+ [^/]+
$regexp = sprintf(
'[^%s%s]+',
preg_quote($defaultSeparator),
$defaultSeparator !== $nextSeparator && '' !== $nextSeparator ? preg_quote($nextSeparator) : ''
);
//如果(没有下一个分隔符 且 不是以路由参数开头) 或者 当前路由参数的后面的字符串为空
if (('' !== $nextSeparator && !preg_match('#^\{[\w\x80-\xFF]+\}#', $followingPattern)) || '' === $followingPattern) {
//这里是优化正则 防止无用的正则回溯
$regexp .= '+';
}
} else {
// 存在正则表达式
//如果正则表达式存在不是utf8编码字符
if (!preg_match('//u', $regexp)) {
$useUtf8 = false;
}
//如果不需要utf8编码 但是这个正则存在utf8编码字符 (这个正则表达式的后半部分我没怎么看懂,整体意思应该是存在utf8编码字符)
elseif (!$needsUtf8 && preg_match('/[\x80-\xFF]|(?<!\\\\)\\\\(?:\\\\\\\\)*+(?-i:X|[pP][\{CLMNPSZ]|x\{[A-Fa-f0-9]{3})/', $regexp)) {
throw new \LogicException(sprintf('Cannot use UTF-8 route requirements without setting the "utf8" option for variable "%s" in pattern "%s".', $varName, $pattern));
}
if (!$useUtf8 && $needsUtf8) {
throw new \LogicException(sprintf('Cannot mix UTF-8 requirement with non-UTF-8 charset for variable "%s" in pattern "%s".', $varName, $pattern));
}
//这里是给有括号的地方在(后面加一个 ?: 不捕获这个 这里就不贴这个代码了
$regexp = self::transformCapturingGroupsToNonCapturings($regexp);
}
//这里就是上面那个"!"
if ($important) {
//最后一位元素标记为true 后面还会说明
//当前token 标记为variable 第二个元素是 前面一位是否是分隔符
$token = ['variable', $isSeparator ? $precedingChar : '', $regexp, $varName, false, true];
} else {
$token = ['variable', $isSeparator ? $precedingChar : '', $regexp, $varName];
}
$tokens[] = $token;
$variables[] = $varName;
}
//这里的意思是最后一段是静态文本
if ($pos < \strlen($pattern)) {
$tokens[] = ['text', substr($pattern, $pos)];
}
//第一个可选的路由参数 先初始化一个值
$firstOptional = \PHP_INT_MAX;
//这里是只处理path
//应该是host上的参数都是必填的吧 不然host就不是正常的host了
if (!$isHost) {
//从后往前面处理 因为如果一个参数后面存在静态文本 就算设置了可选 也是不生效的 也是需要必填的
for ($i = \count($tokens) - 1; $i >= 0; --$i) {
$token = $tokens[$i];
// variable is optional when it is not important and has a default value
//!($token[5] ?? false) 这个就是那个"!"的作用 如果设置了"!" 那前面的参数就算有"?"也会不生效了 感叹号感觉就是必填的意思(如果没有感叹号和问号都没有 也是必填)
if ('variable' === $token[0] && !($token[5] ?? false) && $route->hasDefault($token[3])) {
$firstOptional = $i;
} else {
break;
}
}
}
//这里就是去组装正则表达式
$regexp = '';
for ($i = 0, $nbToken = \count($tokens); $i < $nbToken; ++$i) {
//编译正则 下面有说明
$regexp .= self::computeRegexp($tokens, $i, $firstOptional);
}
$regexp = '{^'.$regexp.'$}sD'.($isHost ? 'i' : '');
// enable Utf8 matching if really required
if ($needsUtf8) {
$regexp .= 'u';
for ($i = 0, $nbToken = \count($tokens); $i < $nbToken; ++$i) {
if ('variable' === $tokens[$i][0]) {
$tokens[$i][4] = true;
}
}
}
return [
//这里是确定路由可能的最长静态前缀
'staticPrefix' => self::determineStaticPrefix($route, $tokens),
'regex' => $regexp,
'tokens' => array_reverse($tokens),
'variables' => $variables,
];
}
private static function computeRegexp(array $tokens, int $index, int $firstOptional): string
{
$token = $tokens[$index];
if ('text' === $token[0]) {
//如果是文本 就直接转义返回
return preg_quote($token[1]);
} else {
// 如果是变量
//这里表示整个path都是路由参数 不然$firstOptional不为0 中间有任何静态文本都不会为0
//我感觉这个if 和直接和else合并 直接使用else中的代码 (不清楚这里有什么特殊含义)
if (0 === $index && 0 === $firstOptional) {
//所以这里是可选 最后一位是?
return sprintf('%s(?P<%s>%s)?', preg_quote($token[1]), $token[3], $token[2]);
} else {
$regexp = sprintf('%s(?P<%s>%s)', preg_quote($token[1]), $token[3], $token[2]);
//如果下标大于等于第一个可选 证明后面的都是可选
if ($index >= $firstOptional) {
//?:不捕获组
$regexp = "(?:$regexp";
$nbTokens = \count($tokens);
if ($nbTokens - 1 == $index) {
//举例 ((()?)?)? 就是前面加了多少个括号 后面就补多少个")?"
$regexp .= str_repeat(')?', $nbTokens - $firstOptional - (0 === $firstOptional ? 1 : 0));
}
}
return $regexp;
}
}
}
在Laravel框架中,只用到了regex这个key,其他key好像没有用到,好了,Symfony路由组件编译就分析完了
回到Illuminate\Routing\RouteCollection
类的match
方法,在这个方法最后还有调用了一个方法,在上面说到最后来分析这个方法
看一下Illuminate\Routing\RouteCollection
类的handleMatchedRoute
方法做了什么处理
protected function handleMatchedRoute(Request $request, $route)
{
if (! is_null($route)) {
return ⑧$route->bind($request);
}
//后续操作就是没有匹配到路由的时候
...
}
⑧看一下Illuminate\Routing\Route
类的bind
方法做了什么处理
public function bind(Request $request)
{
//这里是编译路由 上面已经分析了
$this->compileRoute();
//这里是解析路由参数
$this->parameters = ⑨(new RouteParameterBinder($this))
->parameters($request);
//这里是原始参数 因为parameters有的参数会转化为模型
$this->originalParameters = $this->parameters;
return $this;
}
⑨看一下Illuminate\Routing\RouteParameterBinder
类的parameters
方法做了什么处理
public function parameters($request)
{
//绑定路径参数
$parameters = $this->bindPathParameters($request);
if (! is_null($this->route->compiled->getHostRegex())) {
//绑定host参数
$parameters = $this->bindHostParameters(
$request, $parameters
);
}
//将null参数替换为其默认值
return $this->replaceDefaults($parameters);
}
protected function bindPathParameters($request)
{
$path = '/'.ltrim($request->decodedPath(), '/');
//这里就是获取捕获组的参数
preg_match($this->route->compiled->getRegex(), $path, $matches);
//匹配key
return $this->matchToKeys(array_slice($matches, 1));
}
protected function bindHostParameters($request, $parameters)
{
//这里就是获取捕获组的参数
preg_match($this->route->compiled->getHostRegex(), $request->getHost(), $matches);
//匹配合并
return array_merge($this->matchToKeys(array_slice($matches, 1)), $parameters);
}
protected function matchToKeys(array $matches)
{
if (empty($parameterNames = $this->route->parameterNames())) {
return [];
}
//取交集
$parameters = array_intersect_key($matches, array_flip($parameterNames));
//过滤空的
return array_filter($parameters, function ($value) {
return is_string($value) && strlen($value) > 0;
});
}
protected function replaceDefaults(array $parameters)
{
foreach ($parameters as $key => $value) {
$parameters[$key] = $value ?? Arr::get($this->route->defaults, $key);
}
//循环默认值数组
foreach ($this->route->defaults as $key => $value) {
if (! isset($parameters[$key])) {
$parameters[$key] = $value;
}
}
return $parameters;
}
看一下Illuminate\Routing\RouteCollection
类的handleMatchedRoute
方法后续做了什么处理
protected function handleMatchedRoute(Request $request, $route)
{
...
//后续操作就是没有匹配到路由的时候
//这里是去获取除了当前请求方法外的剩余的方法 去里面找看能否找到匹配的
$others = $this->checkForAlternateVerbs($request);
if (count($others) > 0) {
return $this->getRouteForMethods($request, $others);
}
throw new NotFoundHttpException(sprintf(
'The route %s could not be found.',
$request->path()
));
}
protected function getRouteForMethods($request, array $methods)
{
//这里是OPTIONS请求
if ($request->isMethod('OPTIONS')) {
return (new Route('OPTIONS', $request->path(), function () use ($methods) {
return new Response('', 200, ['Allow' => implode(',', $methods)]);
}))->bind($request);
}
//这里就是抛出方法不被允许的异常
$this->requestMethodNotAllowed($request, $methods, $request->method());
}
protected function requestMethodNotAllowed($request, array $others, $method)
{
throw new MethodNotAllowedHttpException(
$others,
sprintf(
'The %s method is not supported for route %s. Supported methods: %s.',
$method,
$request->path(),
implode(', ', $others)
)
);
}
以上就是路由匹配大概流程了,如果有写的有误的地方,请大佬们指正
本作品采用《CC 协议》,转载必须注明作者和本文链接
666
牛逼
牛逼啊。这个路由匹配太复杂了,不知道换成前缀树匹配会不会简单一些。