NumberFilter.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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\NumberType;
  12. use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
  13. class NumberFilter 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) || !is_numeric($data['value'])) {
  21. return;
  22. }
  23. $type = isset($data['type']) ? $data['type'] : false;
  24. $operator = $this->getOperator($type);
  25. if (!$operator) {
  26. $operator = '=';
  27. }
  28. // c.name > '1' => c.name OPERATOR :FIELDNAME
  29. $parameterName = $this->getNewParameterName($queryBuilder);
  30. $this->applyWhere($queryBuilder, sprintf('%s.%s %s :%s', $alias, $field, $operator, $parameterName));
  31. $queryBuilder->setParameter($parameterName, $data['value']);
  32. }
  33. /**
  34. * @param string $type
  35. *
  36. * @return bool
  37. */
  38. private function getOperator($type)
  39. {
  40. $choices = array(
  41. NumberType::TYPE_EQUAL => '=',
  42. NumberType::TYPE_GREATER_EQUAL => '>=',
  43. NumberType::TYPE_GREATER_THAN => '>',
  44. NumberType::TYPE_LESS_EQUAL => '<=',
  45. NumberType::TYPE_LESS_THAN => '<',
  46. );
  47. return isset($choices[$type]) ? $choices[$type] : false;
  48. }
  49. /**
  50. * {@inheritdoc}
  51. */
  52. public function getDefaultOptions()
  53. {
  54. return array();
  55. }
  56. /**
  57. * {@inheritdoc}
  58. */
  59. public function getRenderSettings()
  60. {
  61. return array('sonata_type_filter_number', array(
  62. 'field_type' => $this->getFieldType(),
  63. 'field_options' => $this->getFieldOptions(),
  64. 'label' => $this->getLabel()
  65. ));
  66. }
  67. }