Each.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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\EachException;
  9. use Respect\Validation\Exceptions\ValidationException;
  10. use Respect\Validation\Helpers\CanValidateIterable;
  11. use Respect\Validation\Validatable;
  12. /**
  13. * Validates whether each value in the input is valid according to another rule.
  14. *
  15. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  16. * @author Henrique Moody <henriquemoody@gmail.com>
  17. * @author Nick Lombard <github@jigsoft.co.za>
  18. * @author William Espindola <oi@williamespindola.com.br>
  19. */
  20. final class Each extends AbstractRule
  21. {
  22. use CanValidateIterable;
  23. /**
  24. * @var Validatable
  25. */
  26. private $rule;
  27. /**
  28. * Initializes the constructor.
  29. */
  30. public function __construct(Validatable $rule)
  31. {
  32. $this->rule = $rule;
  33. }
  34. /**
  35. * {@inheritDoc}
  36. */
  37. public function assert($input): void
  38. {
  39. if (!$this->isIterable($input)) {
  40. throw $this->reportError($input);
  41. }
  42. $exceptions = [];
  43. foreach ($input as $value) {
  44. try {
  45. $this->rule->assert($value);
  46. } catch (ValidationException $exception) {
  47. $exceptions[] = $exception;
  48. }
  49. }
  50. if (!empty($exceptions)) {
  51. /** @var EachException $eachException */
  52. $eachException = $this->reportError($input);
  53. $eachException->addChildren($exceptions);
  54. throw $eachException;
  55. }
  56. }
  57. /**
  58. * {@inheritDoc}
  59. */
  60. public function check($input): void
  61. {
  62. if (!$this->isIterable($input)) {
  63. throw $this->reportError($input);
  64. }
  65. foreach ($input as $value) {
  66. $this->rule->check($value);
  67. }
  68. }
  69. /**
  70. * {@inheritDoc}
  71. */
  72. public function validate($input): bool
  73. {
  74. try {
  75. $this->check($input);
  76. } catch (ValidationException $exception) {
  77. return false;
  78. }
  79. return true;
  80. }
  81. }