FormBuilderIterator.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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. protected static $reflection;
  20. protected $formBuilder;
  21. protected $keys = array();
  22. protected $prefix;
  23. protected $iterator;
  24. /**
  25. * @param \Symfony\Component\Form\FormBuilderInterface $formBuilder
  26. * @param bool $prefix
  27. */
  28. public function __construct(FormBuilderInterface $formBuilder, $prefix = false)
  29. {
  30. $this->formBuilder = $formBuilder;
  31. $this->prefix = $prefix ? $prefix : $formBuilder->getName();
  32. $this->iterator = new \ArrayIterator(self::getKeys($formBuilder));
  33. }
  34. /**
  35. * @static
  36. *
  37. * @param \Symfony\Component\Form\FormBuilderInterface $formBuilder
  38. *
  39. * @return array
  40. */
  41. private static function getKeys(FormBuilderInterface $formBuilder)
  42. {
  43. if (!self::$reflection) {
  44. self::$reflection = new \ReflectionProperty(get_class($formBuilder), 'children');
  45. self::$reflection->setAccessible(true);
  46. }
  47. return array_keys(self::$reflection->getValue($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. }