ChoiceFilter.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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\AdminBundle\Filter\ORM;
  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. $this->applyWhere($queryBuilder, sprintf('%s.%s = :%s', $alias, $field, $this->getName()));
  44. $queryBuilder->setParameter($this->getName(), $data['value']);
  45. }
  46. }
  47. /**
  48. * @param $type
  49. * @return bool
  50. */
  51. private function getOperator($type)
  52. {
  53. $choices = array(
  54. ChoiceType::TYPE_CONTAINS => 'IN',
  55. ChoiceType::TYPE_NOT_CONTAINS => 'NOT IN',
  56. ChoiceType::TYPE_EQUAL => '=',
  57. );
  58. return isset($choices[$type]) ? $choices[$type] : false;
  59. }
  60. /**
  61. * @return array
  62. */
  63. function getDefaultOptions()
  64. {
  65. return array();
  66. }
  67. public function getRenderSettings()
  68. {
  69. return array('sonata_type_filter_default', array(
  70. 'operator_type' => 'sonata_type_boolean',
  71. 'field_type' => $this->getFieldType(),
  72. 'field_options' => $this->getFieldOptions(),
  73. ));
  74. }
  75. }