Skip to content

Instantly share code, notes, and snippets.

@jgornick
Created January 28, 2014 16:57
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jgornick/8671644 to your computer and use it in GitHub Desktop.
Save jgornick/8671644 to your computer and use it in GitHub Desktop.
Doctrine: Criteria Array to Doctrine QueryBuilder
<?php
/**
* Recursively takes the specified criteria and adds too the expression.
*
* The criteria is defined in an array notation where each item in the list
* represents a comparison <fieldName, operator, value>. The operator maps to
* comparison methods located in ExpressionBuilder. The key in the array can
* be used to identify grouping of comparisons.
*
* @example
* $criteria = array(
* 'or' => array(
* array('field1', 'like', '%field1Value%'),
* array('field2', 'like', '%field2Value%')
* ),
* 'and' => array(
* array('field3', 'eq', 3),
* array('field4', 'eq', 'four')
* ),
* array('field5', 'neq', 5)
* );
*
* $qb = new QueryBuilder();
* addCriteria($qb, $qb->expr()->andX(), $criteria);
* echo $qb->getSQL();
*
* // Result:
* // SELECT *
* // FROM tableName
* // WHERE ((field1 LIKE '%field1Value%') OR (field2 LIKE '%field2Value%'))
* // AND ((field3 = '3') AND (field4 = 'four'))
* // AND (field5 <> '5')
*
* @param QueryBuilder $qb
* @param CompositeExpression $expr
* @param array $criteria
*/
function addCriteria(QueryBuilder $qb, CompositeExpression $expr, array $criteria)
{
if (count($criteria)) {
foreach ($criteria as $expression => $comparison) {
list($field, $operator, $value) = $comparison;
if ($expression === 'or') {
$expr->add($this->addCriteria(
$qb,
$qb->expr()->orX(),
$comparison
));
} else if ($expression === 'and') {
$expr->add($this->addCriteria(
$qb,
$qb->expr()->andX(),
$comparison
));
} else {
$expr->add($qb->expr()->{$operator}($field, $qb->expr()->literal($value)));
}
}
}
return $expr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment