AnyOf.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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\Rules;
  8. use Respect\Validation\Exceptions\AnyOfException;
  9. use Respect\Validation\Exceptions\ValidationException;
  10. use function count;
  11. /**
  12. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  13. * @author Henrique Moody <henriquemoody@gmail.com>
  14. */
  15. final class AnyOf extends AbstractComposite
  16. {
  17. /**
  18. * {@inheritDoc}
  19. */
  20. public function assert($input): void
  21. {
  22. $validators = $this->getRules();
  23. $exceptions = $this->getAllThrownExceptions($input);
  24. $numRules = count($validators);
  25. $numExceptions = count($exceptions);
  26. if ($numExceptions === $numRules) {
  27. /** @var AnyOfException $anyOfException */
  28. $anyOfException = $this->reportError($input);
  29. $anyOfException->addChildren($exceptions);
  30. throw $anyOfException;
  31. }
  32. }
  33. /**
  34. * {@inheritDoc}
  35. */
  36. public function validate($input): bool
  37. {
  38. foreach ($this->getRules() as $v) {
  39. if ($v->validate($input)) {
  40. return true;
  41. }
  42. }
  43. return false;
  44. }
  45. /**
  46. * {@inheritDoc}
  47. */
  48. public function check($input): void
  49. {
  50. foreach ($this->getRules() as $v) {
  51. try {
  52. $v->check($input);
  53. return;
  54. } catch (ValidationException $e) {
  55. if (!isset($firstException)) {
  56. $firstException = $e;
  57. }
  58. }
  59. }
  60. if (isset($firstException)) {
  61. throw $firstException;
  62. }
  63. throw $this->reportError($input);
  64. }
  65. }