StringFilter.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 Sonata\AdminBundle\Form\Type\Filter\StringType;
  12. class StringFilter extends Filter
  13. {
  14. /**
  15. * @param QueryBuilder $queryBuilder
  16. * @param string $alias
  17. * @param string $field
  18. * @param string $value
  19. * @return
  20. */
  21. public function filter($queryBuilder, $alias, $field, $value)
  22. {
  23. if (!is_array($value)) {
  24. return;
  25. }
  26. $value['text'] = trim($value['text']);
  27. if (strlen($value['text']) == 0) {
  28. return;
  29. }
  30. $operator = $this->getOperator((int) $value['type']);
  31. if (!$operator) {
  32. $operator = 'LIKE';
  33. }
  34. // c.name > '1' => c.name OPERATOR :FIELDNAME
  35. $queryBuilder->andWhere(sprintf('%s.%s %s :%s', $alias, $field, $operator, $this->getName()));
  36. if ($value['type'] == StringType::TYPE_EQUAL) {
  37. $queryBuilder->setParameter($this->getName(), $value['text']);
  38. } else {
  39. $queryBuilder->setParameter($this->getName(), sprintf($this->getOption('format'), $value['text']));
  40. }
  41. }
  42. /**
  43. * @param $type
  44. * @return bool
  45. */
  46. private function getOperator($type)
  47. {
  48. $choices = array(
  49. StringType::TYPE_CONTAINS => 'LIKE',
  50. StringType::TYPE_NOT_CONTAINS => 'NOT LIKE',
  51. StringType::TYPE_EQUAL => '=',
  52. );
  53. return isset($choices[$type]) ? $choices[$type] : false;
  54. }
  55. /**
  56. * @return array
  57. */
  58. public function getDefaultOptions()
  59. {
  60. return array(
  61. 'format' => '%%%s%%'
  62. );
  63. }
  64. }