DatagridMapper.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. public function __construct(DatagridBuilderInterface $datagridBuilder, DatagridInterface $datagrid, AdminInterface $admin)
  27. {
  28. $this->datagridBuilder = $datagridBuilder;
  29. $this->datagrid = $datagrid;
  30. $this->admin = $admin;
  31. }
  32. /**
  33. * @throws \RuntimeException
  34. * @param string $name
  35. * @param array $fieldDescriptionOptions
  36. * @return \Sonata\AdminBundle\Datagrid\DatagridMapper
  37. */
  38. public function add($name, $type = null, array $fieldDescriptionOptions = array())
  39. {
  40. if ($name instanceof FieldDescriptionInterface) {
  41. $fieldDescription = $name;
  42. $fieldDescription->mergeOptions($fieldDescriptionOptions);
  43. } else if (is_string($name) && !$this->admin->hasFormFieldDescription($name)) {
  44. $fieldDescription = $this->admin->getModelManager()->getNewFieldDescriptionInstance(
  45. $this->admin->getClass(),
  46. $name,
  47. $fieldDescriptionOptions
  48. );
  49. } else {
  50. throw new \RuntimeException('invalid state');
  51. }
  52. // add the field with the DatagridBuilder
  53. $this->datagridBuilder->addFilter($this->datagrid, $type, $fieldDescription, $this->admin);
  54. return $this;
  55. }
  56. /**
  57. * @param string $name
  58. * @return
  59. */
  60. public function get($name)
  61. {
  62. return $this->datagrid->get($name);
  63. }
  64. /**
  65. * @param string $key
  66. * @return boolean
  67. */
  68. public function has($key)
  69. {
  70. return $this->datagrid->has($key);
  71. }
  72. /**
  73. * @param string $key
  74. * @return void
  75. */
  76. public function remove($key)
  77. {
  78. $this->admin->removeFilterFieldDescription($key);
  79. $this->datagrid->remove($key);
  80. }
  81. }