ConstraintViolationList.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Validator;
  11. /**
  12. * An array-acting object that holds many ConstrainViolation instances.
  13. */
  14. class ConstraintViolationList implements \IteratorAggregate, \Countable, \ArrayAccess
  15. {
  16. protected $violations = array();
  17. /**
  18. * @return string
  19. */
  20. public function __toString()
  21. {
  22. $string = '';
  23. foreach ($this->violations as $violation) {
  24. $root = $violation->getRoot();
  25. $class = is_object($root) ? get_class($root) : $root;
  26. $string .= <<<EOF
  27. {$class}.{$violation->getPropertyPath()}:
  28. {$violation->getMessage()}
  29. EOF;
  30. }
  31. return $string;
  32. }
  33. /**
  34. * Add a ConstraintViolation to this list.
  35. *
  36. * @param ConstraintViolation $violation
  37. */
  38. public function add(ConstraintViolation $violation)
  39. {
  40. $this->violations[] = $violation;
  41. }
  42. /**
  43. * Merge an existing ConstraintViolationList into this list.
  44. *
  45. * @param ConstraintViolationList $violations
  46. */
  47. public function addAll(ConstraintViolationList $violations)
  48. {
  49. foreach ($violations->violations as $violation) {
  50. $this->violations[] = $violation;
  51. }
  52. }
  53. /**
  54. * @see IteratorAggregate
  55. */
  56. public function getIterator()
  57. {
  58. return new \ArrayIterator($this->violations);
  59. }
  60. /**
  61. * @see Countable
  62. */
  63. public function count()
  64. {
  65. return count($this->violations);
  66. }
  67. /**
  68. * @see ArrayAccess
  69. */
  70. public function offsetExists($offset)
  71. {
  72. return isset($this->violations[$offset]);
  73. }
  74. /**
  75. * @see ArrayAccess
  76. */
  77. public function offsetGet($offset)
  78. {
  79. return isset($this->violations[$offset]) ? $this->violations[$offset] : null;
  80. }
  81. /**
  82. * @see ArrayAccess
  83. */
  84. public function offsetSet($offset, $value)
  85. {
  86. if (null === $offset) {
  87. $this->violations[] = $value;
  88. } else {
  89. $this->violations[$offset] = $value;
  90. }
  91. }
  92. /**
  93. * @see ArrayAccess
  94. */
  95. public function offsetUnset($offset)
  96. {
  97. unset($this->violations[$offset]);
  98. }
  99. }