Validator.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. /*
  3. * Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
  4. * SPDX-License-Identifier: MIT
  5. */
  6. declare(strict_types=1);
  7. namespace Respect\Validation;
  8. use Respect\Validation\Exceptions\ComponentException;
  9. use Respect\Validation\Exceptions\ValidationException;
  10. use Respect\Validation\Rules\AllOf;
  11. use function count;
  12. /**
  13. * @mixin StaticValidator
  14. *
  15. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  16. * @author Henrique Moody <henriquemoody@gmail.com>
  17. */
  18. final class Validator extends AllOf
  19. {
  20. /**
  21. * Create instance validator.
  22. */
  23. public static function create(): self
  24. {
  25. return new self();
  26. }
  27. /**
  28. * {@inheritDoc}
  29. */
  30. public function check($input): void
  31. {
  32. try {
  33. parent::check($input);
  34. } catch (ValidationException $exception) {
  35. if (count($this->getRules()) == 1 && $this->template) {
  36. $exception->updateTemplate($this->template);
  37. }
  38. throw $exception;
  39. }
  40. }
  41. /**
  42. * Creates a new Validator instance with a rule that was called on the static method.
  43. *
  44. * @param mixed[] $arguments
  45. *
  46. * @throws ComponentException
  47. */
  48. public static function __callStatic(string $ruleName, array $arguments): self
  49. {
  50. return self::create()->__call($ruleName, $arguments);
  51. }
  52. /**
  53. * Create a new rule by the name of the method and adds the rule to the chain.
  54. *
  55. * @param mixed[] $arguments
  56. *
  57. * @throws ComponentException
  58. */
  59. public function __call(string $ruleName, array $arguments): self
  60. {
  61. $this->addRule(Factory::getDefaultInstance()->rule($ruleName, $arguments));
  62. return $this;
  63. }
  64. /**
  65. * 按照规则检查输入,如果不符合规则则抛出异常
  66. *
  67. * @param array $input
  68. * @param array $rules
  69. * @return array
  70. */
  71. public static function input(array $input, array $rules)
  72. {
  73. $values = [];
  74. foreach ($rules as $field => $rule) {
  75. if(is_array($rule) || !($rule instanceof \Respect\Validation\Validator)){
  76. $values[$field] = $rule;
  77. }else{
  78. $value = $rule->defaultType?$rule->default:($input[$field] ?? $rule->default);
  79. $rule->check($value);
  80. $values[$field] = $value;
  81. }
  82. }
  83. return $values;
  84. }
  85. }