BooleanFilter.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 Sonata\AdminBundle\Form\Type\BooleanType;
  12. use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
  13. class BooleanFilter extends Filter
  14. {
  15. /**
  16. * {@inheritdoc}
  17. */
  18. public function filter(ProxyQueryInterface $queryBuilder, $alias, $field, $data)
  19. {
  20. if (!$data || !is_array($data) || !array_key_exists('type', $data) || !array_key_exists('value', $data)) {
  21. return;
  22. }
  23. if (is_array($data['value'])) {
  24. $values = array();
  25. foreach ($data['value'] as $v) {
  26. if (!in_array($v, array(BooleanType::TYPE_NO, BooleanType::TYPE_YES))) {
  27. continue;
  28. }
  29. $values[] = ($v == BooleanType::TYPE_YES) ? 1 : 0;
  30. }
  31. if (count($values) == 0) {
  32. return;
  33. }
  34. $this->applyWhere($queryBuilder, $queryBuilder->expr()->in(sprintf('%s.%s', $alias, $field), $values));
  35. } else {
  36. if (!in_array($data['value'], array(BooleanType::TYPE_NO, BooleanType::TYPE_YES))) {
  37. return;
  38. }
  39. $parameterName = $this->getNewParameterName($queryBuilder);
  40. $this->applyWhere($queryBuilder, sprintf('%s.%s = :%s', $alias, $field, $parameterName));
  41. $queryBuilder->setParameter($parameterName, ($data['value'] == BooleanType::TYPE_YES) ? 1 : 0);
  42. }
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public function getDefaultOptions()
  48. {
  49. return array();
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function getRenderSettings()
  55. {
  56. return array('sonata_type_filter_default', array(
  57. 'field_type' => $this->getFieldType(),
  58. 'field_options' => $this->getFieldOptions(),
  59. 'operator_type' => 'hidden',
  60. 'operator_options' => array(),
  61. 'label' => $this->getLabel()
  62. ));
  63. }
  64. }