FormBuilderIterator.php 2.3 KB

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