DatagridMapper.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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\AdminBundle\Datagrid;
  12. use Sonata\AdminBundle\Admin\AdminInterface;
  13. use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
  14. use Sonata\AdminBundle\Model\ModelManagerInterface;
  15. use Sonata\AdminBundle\Datagrid\DatagridInterface;
  16. use Sonata\AdminBundle\Builder\DatagridBuilderInterface;
  17. /**
  18. * This class is use to simulate the Form API
  19. *
  20. */
  21. class DatagridMapper
  22. {
  23. protected $datagridBuilder;
  24. protected $datagrid;
  25. protected $admin;
  26. /**
  27. * @param \Sonata\AdminBundle\Builder\DatagridBuilderInterface $datagridBuilder
  28. * @param DatagridInterface $datagrid
  29. * @param \Sonata\AdminBundle\Admin\AdminInterface $admin
  30. */
  31. public function __construct(DatagridBuilderInterface $datagridBuilder, DatagridInterface $datagrid, AdminInterface $admin)
  32. {
  33. $this->datagridBuilder = $datagridBuilder;
  34. $this->datagrid = $datagrid;
  35. $this->admin = $admin;
  36. }
  37. /**
  38. * @throws \RuntimeException
  39. * @param mixed $name
  40. * @param mixed $type
  41. * @param array $fieldDescriptionOptions
  42. * @return DatagridMapper
  43. */
  44. public function add($name, $type = null, array $fieldDescriptionOptions = array())
  45. {
  46. if ($name instanceof FieldDescriptionInterface) {
  47. $fieldDescription = $name;
  48. $fieldDescription->mergeOptions($fieldDescriptionOptions);
  49. } else if (is_string($name) && !$this->admin->hasFilterFieldDescription($name)) {
  50. $fieldDescription = $this->admin->getModelManager()->getNewFieldDescriptionInstance(
  51. $this->admin->getClass(),
  52. $name,
  53. $fieldDescriptionOptions
  54. );
  55. } else {
  56. throw new \RuntimeException('invalid state');
  57. }
  58. // add the field with the DatagridBuilder
  59. $this->datagridBuilder->addFilter($this->datagrid, $type, $fieldDescription, $this->admin);
  60. return $this;
  61. }
  62. /**
  63. * @param string $name
  64. * @return
  65. */
  66. public function get($name)
  67. {
  68. return $this->datagrid->get($name);
  69. }
  70. /**
  71. * @param string $key
  72. * @return boolean
  73. */
  74. public function has($key)
  75. {
  76. return $this->datagrid->has($key);
  77. }
  78. /**
  79. * @param string $key
  80. * @return void
  81. */
  82. public function remove($key)
  83. {
  84. $this->admin->removeFilterFieldDescription($key);
  85. $this->datagrid->remove($key);
  86. }
  87. }