|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace MicroPHP\Framework\Dto; |
| 6 | + |
| 7 | +use MicroPHP\Data\Util\Str; |
| 8 | +use MicroPHP\Framework\Dto\Request\BaseReq; |
| 9 | +use MicroPHP\Framework\Exception\ValidateException; |
| 10 | +use Symfony\Component\Validator\Constraint; |
| 11 | +use Symfony\Component\Validator\Constraints\NotNull; |
| 12 | +use Symfony\Component\Validator\ConstraintViolationListInterface; |
| 13 | +use Symfony\Component\Validator\Mapping\ClassMetadata; |
| 14 | +use Symfony\Component\Validator\Validation; |
| 15 | + |
| 16 | +trait ConstraintsTrait |
| 17 | +{ |
| 18 | + /** |
| 19 | + * @var null|array<string, Constraint> |
| 20 | + */ |
| 21 | + protected static ?array $_constraints = null; |
| 22 | + |
| 23 | + /** |
| 24 | + * 添加默认验证器 |
| 25 | + */ |
| 26 | + public function _initConstraints(): void |
| 27 | + { |
| 28 | + if (is_null($this::$_constraints)) { |
| 29 | + $attributeRules = []; |
| 30 | + foreach ($this->getStaticReflection()->getProperties() as $property) { |
| 31 | + if ($this->isInsideProperty($property)) { |
| 32 | + continue; |
| 33 | + } |
| 34 | + $snakePropertyName = Str::snake($property->getName()); |
| 35 | + if (! $property->getType()->allowsNull() && ! $property->hasDefaultValue()) { |
| 36 | + $attributeRules[$snakePropertyName][] = [new NotNull()]; |
| 37 | + } |
| 38 | + } |
| 39 | + $this::$_constraints = $attributeRules; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * 自定义验证器 |
| 45 | + */ |
| 46 | + public static function loadValidatorMetadata(?ClassMetadata $metadata = null): void |
| 47 | + { |
| 48 | + foreach (static::$_constraints ?: [] as $property => $constraints) { |
| 49 | + $metadata->addPropertyConstraint($property, $constraints); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * @throws ValidateException |
| 55 | + */ |
| 56 | + protected function validate(BaseReq $data): void |
| 57 | + { |
| 58 | + $data->_initConstraints(); |
| 59 | + $validator = Validation::createValidatorBuilder() |
| 60 | + ->enableAttributeMapping() |
| 61 | + ->getValidator(); |
| 62 | + $this->throw($validator->validate($data)); |
| 63 | + $this->throw($validator->validate($data)); |
| 64 | + } |
| 65 | + |
| 66 | + /** |
| 67 | + * @throws ValidateException |
| 68 | + */ |
| 69 | + protected function throw(ConstraintViolationListInterface $errors): void |
| 70 | + { |
| 71 | + foreach ($errors as $violation) { |
| 72 | + throw new ValidateException($violation->getPropertyPath() . ': ' . $violation->getMessage() . PHP_EOL); |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments