PageRenderTime 35ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/library/Rules/Each.php

http://github.com/Respect/Validation
PHP | 86 lines | 44 code | 13 blank | 29 comment | 2 complexity | e73f4070cc4de76d0176564df792878f MD5 | raw file
Possible License(s): MIT, BSD-3-Clause
  1. <?php
  2. /*
  3. * This file is part of Respect/Validation.
  4. *
  5. * (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
  6. *
  7. * For the full copyright and license information, please view the LICENSE file
  8. * that was distributed with this source code.
  9. */
  10. declare(strict_types=1);
  11. namespace Respect\Validation\Rules;
  12. use Respect\Validation\Exceptions\EachException;
  13. use Respect\Validation\Exceptions\ValidationException;
  14. use Respect\Validation\Helpers\CanValidateIterable;
  15. use Respect\Validation\Validatable;
  16. /**
  17. * Validates whether each value in the input is valid according to another rule.
  18. *
  19. * @author Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
  20. * @author Henrique Moody <henriquemoody@gmail.com>
  21. * @author Nick Lombard <github@jigsoft.co.za>
  22. * @author William Espindola <oi@williamespindola.com.br>
  23. */
  24. final class Each extends AbstractRule
  25. {
  26. use CanValidateIterable;
  27. /**
  28. * @var Validatable
  29. */
  30. private $rule;
  31. /**
  32. * Initializes the constructor.
  33. */
  34. public function __construct(Validatable $rule)
  35. {
  36. $this->rule = $rule;
  37. }
  38. /**
  39. * {@inheritDoc}
  40. */
  41. public function assert($input): void
  42. {
  43. if (!$this->isIterable($input)) {
  44. throw $this->reportError($input);
  45. }
  46. $exceptions = [];
  47. foreach ($input as $value) {
  48. try {
  49. $this->rule->check($value);
  50. } catch (ValidationException $exception) {
  51. $exceptions[] = $exception;
  52. }
  53. }
  54. if (!empty($exceptions)) {
  55. /** @var EachException $eachException */
  56. $eachException = $this->reportError($input);
  57. $eachException->addChildren($exceptions);
  58. throw $eachException;
  59. }
  60. }
  61. /**
  62. * {@inheritDoc}
  63. */
  64. public function validate($input): bool
  65. {
  66. try {
  67. $this->assert($input);
  68. } catch (ValidationException $exception) {
  69. return false;
  70. }
  71. return true;
  72. }
  73. }