封装优化
This commit is contained in:
67
extend/Aether/PHP/Hyperf/AbstractValidator.php
Normal file
67
extend/Aether/PHP/Hyperf/AbstractValidator.php
Normal file
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Aether;
|
||||
|
||||
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
|
||||
use Hyperf\Validation\Validator;
|
||||
use Hyperf\Di\Annotation\Inject;
|
||||
|
||||
abstract class AbstractValidator
|
||||
{
|
||||
#[Inject]
|
||||
protected ValidatorFactoryInterface $validationFactory;
|
||||
|
||||
/**
|
||||
* 验证场景规则
|
||||
* @var array
|
||||
*/
|
||||
protected array $scenes = [];
|
||||
|
||||
/**
|
||||
* 默认验证规则
|
||||
* @var array
|
||||
*/
|
||||
protected array $rules = [];
|
||||
|
||||
/**
|
||||
* 验证消息
|
||||
* @var array
|
||||
*/
|
||||
protected array $messages = [];
|
||||
|
||||
/**
|
||||
* 属性名称
|
||||
* @var array
|
||||
*/
|
||||
protected array $attributes = [];
|
||||
|
||||
/**
|
||||
* 获取验证器实例
|
||||
*/
|
||||
public function scene(string $scene, array $data): Validator
|
||||
{
|
||||
$rules = $this->getSceneRules($scene);
|
||||
return $this->validationFactory->make($data, $rules, $this->messages, $this->attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取场景验证规则
|
||||
*/
|
||||
protected function getSceneRules(string $scene): array
|
||||
{
|
||||
if (empty($this->scenes[$scene])) {
|
||||
return $this->rules;
|
||||
}
|
||||
|
||||
$sceneRules = [];
|
||||
foreach ($this->scenes[$scene] as $field) {
|
||||
if (isset($this->rules[$field])) {
|
||||
$sceneRules[$field] = $this->rules[$field];
|
||||
}
|
||||
}
|
||||
|
||||
return $sceneRules;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user