Support to rewrite the rules for scene when using validation.#7469
Merged
limingxinleo merged 9 commits intohyperf:masterfrom Sep 25, 2025
Merged
Support to rewrite the rules for scene when using validation.#7469limingxinleo merged 9 commits intohyperf:masterfrom
limingxinleo merged 9 commits intohyperf:masterfrom
Conversation
Member
代码评审报告概述此PR为Hyperf的验证器功能增加了在场景(scene)中直接定义规则的能力,允许覆盖默认规则。这解决了多接口使用相同字段但验证规则不同的问题。 代码质量分析正面方面:
需要改进的方面: 1. 代码质量问题
2. 潜在的功能问题
3. 性能考虑
具体改进建议protected function getRules(): array
{
$rules = $this->rules();
$scene = $this->getScene();
if (\!$scene || \!isset($this->scenes[$scene]) || \!is_array($this->scenes[$scene])) {
return $rules;
}
$sceneRules = [];
$availableRuleKeys = array_keys($rules);
foreach ($this->scenes[$scene] as $fieldName => $ruleDefinition) {
// 如果是数组形式(field => rules),直接覆盖规则
if (is_string($fieldName) && is_array($ruleDefinition)) {
$sceneRules[$fieldName] = $ruleDefinition;
}
// 如果是字符串形式(引用现有规则)
elseif (is_numeric($fieldName) && is_string($ruleDefinition) && in_array($ruleDefinition, $availableRuleKeys)) {
$sceneRules[$ruleDefinition] = $rules[$ruleDefinition];
}
}
return $sceneRules;
}测试覆盖率
安全考虑
总体评价这是一个有价值的功能增强,解决了实际问题。但需要:
建议: 在合并前完善测试用例和代码优化。 🤖 Generated with Claude Code |
…ation/scene_rules
limingxinleo
previously approved these changes
Sep 25, 2025
limingxinleo
approved these changes
Sep 25, 2025
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
例如使用validation功能的以下场景时:
之前版本是会报错。如果删除$scenes["detail"]["phone"]的赋值后,会正常使用,但是场景只能引用下面定义的phone规则。
有时会遇到,A接口和B接口都需要用phone,但是A接口phone是必填,B接口phone是非必填,但是如果填写的话就需要走phone的规则。 如果用其他方式实现会比较复杂,例如创建一个新的验证器,那么message和attributes的方法都要复制过去。再或者写很多方法去进行手动验证,这样极不方便解耦和提高效率。
所以如果在scenes中可以直接将场景的使用的参数进行覆盖就可以大大减少很多工作量。