FormBuilderIterator.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. /*
  3. * This file is part of the Sonata project.
  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\FormBuilder;
  12. class FormBuilderIterator extends \RecursiveArrayIterator
  13. {
  14. protected static $reflection;
  15. protected $formBuilder;
  16. protected $keys = array();
  17. protected $prefix;
  18. protected $iterator;
  19. /**
  20. * @param \Symfony\Component\Form\FormBuilder $formBuilder
  21. * @param bool $prefix
  22. */
  23. public function __construct(FormBuilder $formBuilder, $prefix = false)
  24. {
  25. $this->formBuilder = $formBuilder;
  26. $this->prefix = $prefix ? $prefix : $formBuilder->getName();
  27. $this->iterator = new \ArrayIterator(self::getKeys($formBuilder));
  28. }
  29. /**
  30. * @static
  31. *
  32. * @param \Symfony\Component\Form\FormBuilder $formBuilder
  33. *
  34. * @return array
  35. */
  36. private static function getKeys(FormBuilder $formBuilder)
  37. {
  38. if (!self::$reflection) {
  39. self::$reflection = new \ReflectionProperty(get_class($formBuilder), 'children');
  40. self::$reflection->setAccessible(true);
  41. }
  42. return array_keys(self::$reflection->getValue($formBuilder));
  43. }
  44. /**
  45. * {@inheritDoc}
  46. */
  47. public function rewind()
  48. {
  49. $this->iterator->rewind();
  50. }
  51. /**
  52. * {@inheritDoc}
  53. */
  54. public function valid()
  55. {
  56. return $this->iterator->valid();
  57. }
  58. /**
  59. * {@inheritDoc}
  60. */
  61. public function key()
  62. {
  63. $name = $this->iterator->current();
  64. return sprintf('%s_%s', $this->prefix, $name);
  65. }
  66. /**
  67. * {@inheritDoc}
  68. */
  69. public function next()
  70. {
  71. $this->iterator->next();
  72. }
  73. /**
  74. * {@inheritDoc}
  75. */
  76. public function current()
  77. {
  78. return $this->formBuilder->get($this->iterator->current());
  79. }
  80. /**
  81. * {@inheritDoc}
  82. */
  83. public function getChildren()
  84. {
  85. return new self($this->formBuilder->get($this->iterator->current()), $this->current());
  86. }
  87. /**
  88. * {@inheritDoc}
  89. */
  90. public function hasChildren()
  91. {
  92. return count(self::getKeys($this->current())) > 0;
  93. }
  94. }