RecursiveExceptionIterator.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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\Exceptions;
  8. use ArrayIterator;
  9. use Countable;
  10. use RecursiveIterator;
  11. use UnexpectedValueException;
  12. /**
  13. * @author Henrique Moody <henriquemoody@gmail.com>
  14. *
  15. * @implements RecursiveIterator<int, ValidationException>
  16. */
  17. final class RecursiveExceptionIterator implements RecursiveIterator, Countable
  18. {
  19. /**
  20. * @var ArrayIterator|ValidationException[]
  21. */
  22. private $exceptions;
  23. public function __construct(NestedValidationException $parent)
  24. {
  25. $this->exceptions = new ArrayIterator($parent->getChildren());
  26. }
  27. public function count(): int
  28. {
  29. return $this->exceptions->count();
  30. }
  31. public function hasChildren(): bool
  32. {
  33. if (!$this->valid()) {
  34. return false;
  35. }
  36. return $this->current() instanceof NestedValidationException;
  37. }
  38. public function getChildren(): self
  39. {
  40. $exception = $this->current();
  41. if (!$exception instanceof NestedValidationException) {
  42. throw new UnexpectedValueException();
  43. }
  44. return new static($exception);
  45. }
  46. /**
  47. * @return ValidationException|NestedValidationException
  48. */
  49. public function current(): ValidationException
  50. {
  51. return $this->exceptions->current();
  52. }
  53. public function key(): int
  54. {
  55. return $this->exceptions->key();
  56. }
  57. public function next(): void
  58. {
  59. $this->exceptions->next();
  60. }
  61. public function rewind(): void
  62. {
  63. $this->exceptions->rewind();
  64. }
  65. public function valid(): bool
  66. {
  67. return $this->exceptions->valid();
  68. }
  69. }