ChoiceFilter.php 2.7 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. 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 (empty($data['value']) || $data['value'] == 'all') {
  41. return;
  42. }
  43. if ($data['type'] == ChoiceType::TYPE_NOT_CONTAINS) {
  44. $this->applyWhere($queryBuilder, sprintf('%s.%s <> :%s', $alias, $field, $this->getName()));
  45. } else {
  46. $this->applyWhere($queryBuilder, sprintf('%s.%s = :%s', $alias, $field, $this->getName()));
  47. }
  48. $queryBuilder->setParameter($this->getName(), $data['value']);
  49. }
  50. }
  51. /**
  52. * @param $type
  53. * @return bool
  54. */
  55. private function getOperator($type)
  56. {
  57. $choices = array(
  58. ChoiceType::TYPE_CONTAINS => 'IN',
  59. ChoiceType::TYPE_NOT_CONTAINS => 'NOT IN',
  60. ChoiceType::TYPE_EQUAL => '=',
  61. );
  62. return isset($choices[$type]) ? $choices[$type] : false;
  63. }
  64. /**
  65. * @return array
  66. */
  67. public function getDefaultOptions()
  68. {
  69. return array();
  70. }
  71. /**
  72. * @return array
  73. */
  74. public function getRenderSettings()
  75. {
  76. return array('sonata_type_filter_default', array(
  77. 'operator_type' => 'sonata_type_boolean',
  78. 'field_type' => $this->getFieldType(),
  79. 'field_options' => $this->getFieldOptions(),
  80. 'label' => $this->getLabel()
  81. ));
  82. }
  83. }