StringFilter.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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\Filter\ChoiceType;
  12. use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
  13. class StringFilter 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('value', $data)) {
  21. return;
  22. }
  23. $data['value'] = trim($data['value']);
  24. if (strlen($data['value']) == 0) {
  25. return;
  26. }
  27. $data['type'] = !isset($data['type']) ? ChoiceType::TYPE_CONTAINS : $data['type'];
  28. $operator = $this->getOperator((int) $data['type']);
  29. if (!$operator) {
  30. $operator = 'LIKE';
  31. }
  32. // c.name > '1' => c.name OPERATOR :FIELDNAME
  33. $parameterName = $this->getNewParameterName($queryBuilder);
  34. $this->applyWhere($queryBuilder, sprintf('%s.%s %s :%s', $alias, $field, $operator, $parameterName));
  35. if ($data['type'] == ChoiceType::TYPE_EQUAL) {
  36. $queryBuilder->setParameter($parameterName, $data['value']);
  37. } else {
  38. $queryBuilder->setParameter($parameterName, sprintf($this->getOption('format'), $data['value']));
  39. }
  40. }
  41. /**
  42. * @param string $type
  43. *
  44. * @return bool
  45. */
  46. private function getOperator($type)
  47. {
  48. $choices = array(
  49. ChoiceType::TYPE_CONTAINS => 'LIKE',
  50. ChoiceType::TYPE_NOT_CONTAINS => 'NOT LIKE',
  51. ChoiceType::TYPE_EQUAL => '=',
  52. );
  53. return isset($choices[$type]) ? $choices[$type] : false;
  54. }
  55. /**
  56. * {@inheritdoc}
  57. */
  58. public function getDefaultOptions()
  59. {
  60. return array(
  61. 'format' => '%%%s%%'
  62. );
  63. }
  64. /**
  65. * {@inheritdoc}
  66. */
  67. public function getRenderSettings()
  68. {
  69. return array('sonata_type_filter_choice', array(
  70. 'field_type' => $this->getFieldType(),
  71. 'field_options' => $this->getFieldOptions(),
  72. 'label' => $this->getLabel()
  73. ));
  74. }
  75. }