ChoiceFilter.php 2.8 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. namespace Sonata\DoctrineORMAdminBundle\Filter;
  11. use Doctrine\ORM\QueryBuilder;
  12. use Sonata\AdminBundle\Form\Type\Filter\ChoiceType;
  13. use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
  14. class ChoiceFilter extends Filter
  15. {
  16. /**
  17. * {@inheritdoc}
  18. */
  19. public function filter(ProxyQueryInterface $queryBuilder, $alias, $field, $data)
  20. {
  21. if (!$data || !is_array($data) || !array_key_exists('type', $data) || !array_key_exists('value', $data)) {
  22. return;
  23. }
  24. if (is_array($data['value'])) {
  25. if (count($data['value']) == 0) {
  26. return;
  27. }
  28. if (in_array('all', $data['value'])) {
  29. return;
  30. }
  31. if ($data['type'] == ChoiceType::TYPE_NOT_CONTAINS) {
  32. $this->applyWhere($queryBuilder, $queryBuilder->expr()->notIn(sprintf('%s.%s', $alias, $field ), $data['value']));
  33. } else {
  34. $this->applyWhere($queryBuilder, $queryBuilder->expr()->in(sprintf('%s.%s', $alias, $field ), $data['value']));
  35. }
  36. } else {
  37. if ($data['value'] === '' || $data['value'] === null || $data['value'] === false || $data['value'] == 'all') {
  38. return;
  39. }
  40. $parameterName = $this->getNewParameterName($queryBuilder);
  41. if ($data['type'] == ChoiceType::TYPE_NOT_CONTAINS) {
  42. $this->applyWhere($queryBuilder, sprintf('%s.%s <> :%s', $alias, $field, $parameterName));
  43. } else {
  44. $this->applyWhere($queryBuilder, sprintf('%s.%s = :%s', $alias, $field, $parameterName));
  45. }
  46. $queryBuilder->setParameter($parameterName, $data['value']);
  47. }
  48. }
  49. /**
  50. * @param string $type
  51. *
  52. * @return bool
  53. */
  54. private function getOperator($type)
  55. {
  56. $choices = array(
  57. ChoiceType::TYPE_CONTAINS => 'IN',
  58. ChoiceType::TYPE_NOT_CONTAINS => 'NOT IN',
  59. ChoiceType::TYPE_EQUAL => '=',
  60. );
  61. return isset($choices[$type]) ? $choices[$type] : false;
  62. }
  63. /**
  64. * {@inheritdoc}
  65. */
  66. public function getDefaultOptions()
  67. {
  68. return array();
  69. }
  70. /**
  71. * {@inheritdoc}
  72. */
  73. public function getRenderSettings()
  74. {
  75. return array('sonata_type_filter_default', array(
  76. 'operator_type' => 'sonata_type_equal',
  77. 'field_type' => $this->getFieldType(),
  78. 'field_options' => $this->getFieldOptions(),
  79. 'label' => $this->getLabel()
  80. ));
  81. }
  82. }