DatagridMapper.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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\Datagrid;
  15. use Sonata\BaseApplicationBundle\Builder\DatagridBuilderInterface;
  16. /**
  17. * This class is use to simulate the Form API
  18. *
  19. */
  20. class DatagridMapper
  21. {
  22. protected $datagridBuilder;
  23. protected $datagrid;
  24. protected $admin;
  25. public function __construct(DatagridBuilderInterface $datagridBuilder, Datagrid $datagrid, Admin $admin)
  26. {
  27. $this->datagridBuilder = $datagridBuilder;
  28. $this->datagrid = $datagrid;
  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->hasFormFieldDescription($name)) {
  37. $fieldDescription = new FieldDescription;
  38. $fieldDescription->setName($name);
  39. $fieldDescription->setOptions($fieldDescriptionOptions);
  40. $this->datagridBuilder->fixFieldDescription($this->admin, $fieldDescription, $fieldDescriptionOptions);
  41. $this->admin->addListFieldDescription($name, $fieldDescription);
  42. } else if (is_string($name) && $this->admin->hasFormFieldDescription($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->datagridBuilder->addFilter(
  49. $this->datagrid,
  50. $fieldDescription
  51. );
  52. }
  53. public function get($name)
  54. {
  55. return $this->datagrid->get($name);
  56. }
  57. public function has($key)
  58. {
  59. return $this->datagrid->has($key);
  60. }
  61. public function remove($key)
  62. {
  63. $this->admin->removeFilterFieldDescription($key);
  64. $this->datagrid->remove($key);
  65. }
  66. }