FormBuilderIterator.php 2.4 KB

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