ListMapper.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /*
  3. * This file is part of the Sonata 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. */
  11. namespace Sonata\BaseApplicationBundle\Datagrid;
  12. use Sonata\BaseApplicationBundle\Admin\Admin;
  13. use Sonata\BaseApplicationBundle\Admin\FieldDescription;
  14. use Sonata\BaseApplicationBundle\Datagrid\ListCollection;
  15. use Sonata\BaseApplicationBundle\Builder\ListBuilderInterface;
  16. /**
  17. * This class is use to simulate the Form API
  18. *
  19. */
  20. class ListMapper
  21. {
  22. protected $listBuilder;
  23. protected $list;
  24. protected $admin;
  25. public function __construct(ListBuilderInterface $listBuilder, ListCollection $list, Admin $admin)
  26. {
  27. $this->listBuilder = $listBuilder;
  28. $this->list = $list;
  29. $this->admin = $admin;
  30. }
  31. public function add($name, array $fieldDescriptionOptions = array())
  32. {
  33. if ($name instanceof FieldDescription) {
  34. $fieldDescription = $name;
  35. $fieldDescription->mergeOptions($fieldDescriptionOptions);
  36. } else if (is_string($name) && !$this->admin->hasListFieldDescription($name)) {
  37. $fieldDescription = new FieldDescription;
  38. $fieldDescription->setOptions($fieldDescriptionOptions);
  39. $fieldDescription->setName($name);
  40. $this->listBuilder->fixFieldDescription($this->admin, $fieldDescription, $fieldDescriptionOptions);
  41. $this->admin->addListFieldDescription($name, $fieldDescription);
  42. } else if (is_string($name) && $this->admin->hasListFieldDescription($name)) {
  43. $fieldDescription = $this->admin->getFormFieldDescription($name);
  44. } else {
  45. throw new \RuntimeException('invalid state');
  46. }
  47. // add the field with the FormBuilder
  48. return $this->listBuilder->addField(
  49. $this->list,
  50. $fieldDescription
  51. );
  52. }
  53. public function get($name)
  54. {
  55. return $this->list->get($name);
  56. }
  57. public function has($key)
  58. {
  59. return $this->list->has($key);
  60. }
  61. public function remove($key)
  62. {
  63. $this->admin->removeListFieldDescription($key);
  64. $this->list->remove($key);
  65. }
  66. }