Skip to content

Instantly share code, notes, and snippets.

@eikes
Forked from dbu/CaseInsensitiveStringFilter.php
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eikes/21f32ff44128c723cdad to your computer and use it in GitHub Desktop.
Save eikes/21f32ff44128c723cdad to your computer and use it in GitHub Desktop.
<?php
namespace Liip\AcmeBundle\Filter;
use Sonata\AdminBundle\Form\Type\Filter\ChoiceType;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use Sonata\DoctrineORMAdminBundle\Filter\StringFilter;
class CaseInsensitiveStringFilter extends StringFilter
{
/**
* {@inheritdoc}
*/
public function filter(ProxyQueryInterface $queryBuilder, $alias, $field, $data)
{
if (!$data || !is_array($data) || !array_key_exists('value', $data)) {
return;
}
$data['value'] = trim($data['value']);
if (strlen($data['value']) == 0) {
return;
}
$data['type'] = !isset($data['type']) ? ChoiceType::TYPE_CONTAINS : $data['type'];
$operator = $this->getOperator((int) $data['type']);
if (!$operator) {
$operator = 'LIKE';
}
// c.name > '1' => c.name OPERATOR :FIELDNAME
$parameterName = $this->getNewParameterName($queryBuilder);
$this->applyWhere($queryBuilder, sprintf('LOWER(%s.%s) %s :%s', $alias, $field, $operator, $parameterName));
if ($data['type'] != ChoiceType::TYPE_EQUAL) {
$data['value'] = sprintf($this->getOption('format'), $data['value']);
}
$queryBuilder->setParameter($parameterName, strtolower($data['value']));
}
/**
* exact copy-paste because private method
*/
private function getOperator($type)
{
$choices = array(
ChoiceType::TYPE_CONTAINS => 'LIKE',
ChoiceType::TYPE_NOT_CONTAINS => 'NOT LIKE',
ChoiceType::TYPE_EQUAL => '=',
);
return isset($choices[$type]) ? $choices[$type] : false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment