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