OneOf.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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\OneOfException;
  9. use Respect\Validation\Exceptions\ValidationException;
  10. use function array_shift;
  11. use function count;
  12. /**
  13. * @author Bradyn Poulsen <bradyn@bradynpoulsen.com>
  14. * @author Henrique Moody <henriquemoody@gmail.com>
  15. */
  16. final class OneOf extends AbstractComposite
  17. {
  18. /**
  19. * {@inheritDoc}
  20. */
  21. public function assert($input): void
  22. {
  23. $validators = $this->getRules();
  24. $exceptions = $this->getAllThrownExceptions($input);
  25. $numRules = count($validators);
  26. $numExceptions = count($exceptions);
  27. if ($numExceptions !== $numRules - 1) {
  28. /** @var OneOfException $oneOfException */
  29. $oneOfException = $this->reportError($input);
  30. $oneOfException->addChildren($exceptions);
  31. throw $oneOfException;
  32. }
  33. }
  34. /**
  35. * {@inheritDoc}
  36. */
  37. public function validate($input): bool
  38. {
  39. $rulesPassedCount = 0;
  40. foreach ($this->getRules() as $rule) {
  41. if (!$rule->validate($input)) {
  42. continue;
  43. }
  44. ++$rulesPassedCount;
  45. }
  46. return $rulesPassedCount === 1;
  47. }
  48. /**
  49. * {@inheritDoc}
  50. */
  51. public function check($input): void
  52. {
  53. $exceptions = [];
  54. $rulesPassedCount = 0;
  55. foreach ($this->getRules() as $rule) {
  56. try {
  57. $rule->check($input);
  58. ++$rulesPassedCount;
  59. } catch (ValidationException $exception) {
  60. $exceptions[] = $exception;
  61. }
  62. }
  63. if ($rulesPassedCount === 1) {
  64. return;
  65. }
  66. throw array_shift($exceptions) ?: $this->reportError($input);
  67. }
  68. }