StringFilter.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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\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. $this->applyWhere($queryBuilder, sprintf('%s.%s %s :%s', $alias, $field, $operator, $this->getName()));
  37. if ($data['type'] == ChoiceType::TYPE_EQUAL) {
  38. $queryBuilder->setParameter($this->getName(), $data['value']);
  39. } else {
  40. $queryBuilder->setParameter($this->getName(), sprintf($this->getOption('format'), $data['value']));
  41. }
  42. }
  43. /**
  44. * @param $type
  45. * @return bool
  46. */
  47. private function getOperator($type)
  48. {
  49. $choices = array(
  50. ChoiceType::TYPE_CONTAINS => 'LIKE',
  51. ChoiceType::TYPE_NOT_CONTAINS => 'NOT LIKE',
  52. ChoiceType::TYPE_EQUAL => '=',
  53. );
  54. return isset($choices[$type]) ? $choices[$type] : false;
  55. }
  56. /**
  57. * @return array
  58. */
  59. public function getDefaultOptions()
  60. {
  61. return array(
  62. 'format' => '%%%s%%'
  63. );
  64. }
  65. public function getRenderSettings()
  66. {
  67. return array('sonata_type_filter_choice', array(
  68. 'field_type' => $this->getFieldType(),
  69. 'field_options' => $this->getFieldOptions(),
  70. 'label' => $this->getLabel()
  71. ));
  72. }
  73. }