Created
March 25, 2014 22:45
-
-
Save eugene1g/9773135 to your computer and use it in GitHub Desktop.
Doctrine2 - creating an expression to sanitize parameters to the LIKE clause
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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) | |
{ | |
//... | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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