Skip to content

Instantly share code, notes, and snippets.

@eugene1g
Created March 25, 2014 22:45
Show Gist options
  • Save eugene1g/9773135 to your computer and use it in GitHub Desktop.
Save eugene1g/9773135 to your computer and use it in GitHub Desktop.
Doctrine2 - creating an expression to sanitize parameters to the LIKE clause
<?php
namespace Foo\Core\Doctrine;
use Doctrine\ORM\Query\Expr as DoctrineExpr;
/**
* Contains custom ORM expressions for comparisons, regexps, case-insensitive matches etc
* Used instead of the regular Query\Expr() class http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class
*/
class Expr extends DoctrineExpr
{
/**
* Creates a LIKE clause after escaping all meaningful symbols within the like token (specifically, % _ and \)
* @return Comparison
*/
public function sanitizedLike($fieldRef, $searchToken, $prefix = '%', $suffix = '%')
{
//escape reserved characters in LIKE [%_\] with the default escape symbol "\"
$cleanToken = addcslashes($searchToken, "%_" . chr(92)); //92 = backslash
$compiledPattern = $prefix . $cleanToken . $suffix;
return $this->like($fieldRef, $this->literal($compiledPattern));
}
public function regexp($x, $y)
{
//...
}
}
<?php
namespace Foo\Entity;
use Doctrine\ORM\EntityRepository;
use Foo\Core\Doctrine\Expr;
class ProductRepository extends EntityRepository
{
/**
* Find Product entities containing searched terms
*
* @param string $term
* @return Product[]
*/
public function findInSearchableFields($term)
{
$expr = new Expr();
return $this->createQueryBuilder('p')
->andWhere($expr->sanitizedLike('p.title',$term))
->getQuery()
->execute();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment