EnumValidator.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. namespace App\Module\Protobuf\Validators;
  3. use UCore\Helper\Logger;
  4. use UCore\Validator;
  5. use Uraus\App\ACCOUNT_TYPE;
  6. /**
  7. * Protobuf枚举value有效验证
  8. *
  9. * @property array $args
  10. */
  11. class EnumValidator extends Validator
  12. {
  13. /**
  14. * 验证传入的value 是否为 传入了Protobuf枚举的的value
  15. * @param mixed $value 待验证的value,
  16. * @param array $data
  17. * @return bool
  18. */
  19. public function validate(mixed $value, array $data): bool
  20. {
  21. if (empty($this->args[0])) {
  22. throw new \Ucore\Exception\CodeException('Missing enum class name');
  23. }
  24. $className = $this->args[0];
  25. if (!class_exists($className)) {
  26. throw new \Ucore\Exception\CodeException("Enum class {$className} not found");
  27. }
  28. if (!property_exists($className, 'valueToName') || !method_exists($className, 'name')) {
  29. throw new \Ucore\Exception\CodeException("Invalid protobuf enum structure: {$className}");
  30. }
  31. try {
  32. $className::value($value);
  33. return true;
  34. } catch (\UnexpectedValueException $e) {
  35. Logger::error('e:'.$e->getMessage());
  36. return false;
  37. }
  38. }
  39. }