FormBuilderIterator.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. public function __construct(FormBuilder $formBuilder, $prefix = false)
  19. {
  20. $this->formBuilder = $formBuilder;
  21. $this->prefix = $prefix ? $prefix : $formBuilder->getName();
  22. $this->iterator = new \ArrayIterator(self::getKeys($formBuilder));
  23. }
  24. private static function getKeys(FormBuilder $formBuilder)
  25. {
  26. if (!self::$reflection) {
  27. self::$reflection = new \ReflectionProperty(get_class($formBuilder), 'children');
  28. self::$reflection->setAccessible(true);
  29. }
  30. return array_keys(self::$reflection->getValue($formBuilder));
  31. }
  32. public function rewind()
  33. {
  34. return $this->iterator->rewind();
  35. }
  36. public function valid()
  37. {
  38. return $this->iterator->valid();
  39. }
  40. public function key()
  41. {
  42. $name = $this->iterator->current();
  43. return sprintf('%s_%s', $this->prefix, $name);
  44. }
  45. public function next()
  46. {
  47. return $this->iterator->next();
  48. }
  49. public function current()
  50. {
  51. return $this->formBuilder->get($this->iterator->current());
  52. }
  53. public function getChildren()
  54. {
  55. return new self($this->formBuilder->get($this->iterator->current()), $this->current());
  56. }
  57. public function hasChildren()
  58. {
  59. return count(self::getKeys($this->current())) > 0;
  60. }
  61. }