ChoiceFilter.php 2.8 KB

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