FormBuilderIterator.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. <?php
  2. /*
  3. * This file is part of the Sonata Project package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  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 Sonata\AdminBundle\Util;
  11. use Symfony\Component\Form\FormBuilderInterface;
  12. /**
  13. * Class FormBuilderIterator.
  14. *
  15. * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  16. */
  17. class FormBuilderIterator extends \RecursiveArrayIterator
  18. {
  19. /**
  20. * @var \ReflectionProperty
  21. */
  22. protected static $reflection;
  23. /**
  24. * @var FormBuilderInterface
  25. */
  26. protected $formBuilder;
  27. /**
  28. * @var array
  29. */
  30. protected $keys = array();
  31. /**
  32. * @var bool|string
  33. */
  34. protected $prefix;
  35. /**
  36. * @var \ArrayIterator
  37. */
  38. protected $iterator;
  39. /**
  40. * @param FormBuilderInterface $formBuilder
  41. * @param bool $prefix
  42. */
  43. public function __construct(FormBuilderInterface $formBuilder, $prefix = false)
  44. {
  45. $this->formBuilder = $formBuilder;
  46. $this->prefix = $prefix ? $prefix : $formBuilder->getName();
  47. $this->iterator = new \ArrayIterator(self::getKeys($formBuilder));
  48. }
  49. /**
  50. * {@inheritdoc}
  51. */
  52. public function rewind()
  53. {
  54. $this->iterator->rewind();
  55. }
  56. /**
  57. * {@inheritdoc}
  58. */
  59. public function valid()
  60. {
  61. return $this->iterator->valid();
  62. }
  63. /**
  64. * {@inheritdoc}
  65. */
  66. public function key()
  67. {
  68. $name = $this->iterator->current();
  69. return sprintf('%s_%s', $this->prefix, $name);
  70. }
  71. /**
  72. * {@inheritdoc}
  73. */
  74. public function next()
  75. {
  76. $this->iterator->next();
  77. }
  78. /**
  79. * {@inheritdoc}
  80. */
  81. public function current()
  82. {
  83. return $this->formBuilder->get($this->iterator->current());
  84. }
  85. /**
  86. * {@inheritdoc}
  87. */
  88. public function getChildren()
  89. {
  90. return new self($this->formBuilder->get($this->iterator->current()), $this->current());
  91. }
  92. /**
  93. * {@inheritdoc}
  94. */
  95. public function hasChildren()
  96. {
  97. return count(self::getKeys($this->current())) > 0;
  98. }
  99. /**
  100. * @static
  101. *
  102. * @param FormBuilderInterface $formBuilder
  103. *
  104. * @return array
  105. */
  106. private static function getKeys(FormBuilderInterface $formBuilder)
  107. {
  108. return array_keys($formBuilder->all());
  109. }
  110. }