source: http://stackoverflow.com/a/12015992/360838 (accessed 2017-04-13)

@param string $query
@param array  $criteria

@return string
344458
public function getStatement(string $query, array $criteria = []): string {
		
		// the ExtendedPdo object uses its parser to manipulate the criteria it
		// receives to do additional tasks like handling arrays for IN () clauses.
		// to try and get as close to the statement that is run against the
		// database as possible, we'll do that here, too.
		
		$parser = $this->dbConn->getParser();
		list($query, $criteria) = $parser->rebuild($query, $criteria);
		
		// now, we'll use the (slightly modified) code from stack overflow
		// (referenced above) to builds a string version of the statement.
		
		$keys = array();
		foreach ($criteria as $key => $value) {
			if (is_string($key)) {
				$keys[] = '/:' . $key . '/';
			} else {
				$keys[] = '/[?]/';
			}
			
			if (is_array($value)) {
				$criteria[$key] = implode(',', $value);
			}
			
			if (is_null($value)) {
				$criteria[$key] = 'NULL';
			}
		}
		
		return preg_replace($keys, $criteria, $query);
	}
424075
public function search(array $criteria = array())
    {

        /** @var Statement $statement */
        $maxResults   = isset($criteria['maxResults']) ? intval($criteria['maxResults']) : self::MAX_RESULTS;
        $where        = isset($criteria['where']) ? $criteria['where'] : null;
        $queryBuilder = $this->getSelectQueryBuilder();
        //        $returnType   = isset($criteria['returnType']) ? $criteria['returnType'] : null;

        // add filter (https://trac.wheregroup.com/cp/issues/3733)
        if (!empty($this->sqlFilter)) {
            $queryBuilder->andWhere($this->sqlFilter);
        }

        // add second filter (https://trac.wheregroup.com/cp/issues/4643)
        if ($where) {
            $queryBuilder->andWhere($where);
        }

        $queryBuilder->setMaxResults($maxResults);
        // $queryBuilder->setParameters($params);
        $statement  = $queryBuilder->execute();
        $rows       = $statement->fetchAll();
        $hasResults = count($rows) > 0;

        // Cast array to DataItem array list
        if ($hasResults) {
            $this->prepareResults($rows);
        }

        return $rows;
    }
668904
public function getFindByQuery(array $criteria = null, array $orderBy = null, $limit = null, $offset = null)
    {
        /** @var \Doctrine\ORM\QueryBuilder $qb */
        $qb = $this->createQueryBuilder('e');

        $firstCriteria = true;
        if (!empty($criteria)) {
            foreach ($criteria as $field => $value) {
                if ($firstCriteria) {
                    if ($value === null or $value === 'null') {
                        $qb->where("e.$field IS NULL");
                    } elseif ($value === 'not null') {
                        $qb->where("e.$field IS NOT NULL");
                    } else {
                        $qb->where("e.$field = :$field");
                        $qb->setParameter($field, $value);
                    }

                    $firstCriteria = false;
                } else {
                    if ($value === null or $value === 'null') {
                        $qb->andWhere("e.$field IS NULL");
                    } elseif ($value === 'not null') {
                        $qb->andWhere("e.$field IS NOT NULL");
                    } else {
                        $qb->andWhere("e.$field = :$field");
                        $qb->setParameter($field, $value);
                    }
                }
            }
        }

        $firstOrderBy = true;
        if (!empty($orderBy)) {
            foreach ($orderBy as $field => $value) {
                if ($firstOrderBy) {
                    $qb->orderBy("e.$field", $value);
                    $firstOrderBy = false;
                } else {
                    $qb->addOrderBy("e.$field", $value);
                }
            }
        }

        if (!empty($limit)) {
            $qb->setMaxResults($limit);
        }

        if (!empty($offset)) {
            $qb->setFirstResult($offset);
        }

        return $qb->getQuery();
    }
1100075
private function getCriteriaAsSting(array $criteria): string
    {
        $criteriaString = '';
        foreach ($criteria as $key => $value) {
            $criteriaString .= $key.': '.$value.', ';
        }

        return substr($criteriaString, 0, -2);
    }
334456
public function deleteBy($criteria)
    {
        $criteria = Util::normalizeCriteria($criteria);

        $queryBuilder = $this->getQueryBuilder($criteria);
        $queryBuilder->delete($this->entityName, 'e');
        $queryBuilder->getQuery()->execute();
    }
1119345
protected function applyCriteria(QueryBuilder $queryBuilder, array $criteria = [])
    {
        foreach ($criteria as $property => $value) {
            $name = $this->getPropertyName($property);
            if (null === $value) {
                $queryBuilder->andWhere($queryBuilder->expr()->isNull($name));
            } elseif (is_array($value)) {
                $queryBuilder->andWhere($queryBuilder->expr()->in($name, $value));
            } elseif ('' !== $value) {
                $parameter = str_replace('.', '_', $property);
                $queryBuilder
                    ->andWhere($queryBuilder->expr()->eq($name, ':'.$parameter))
                    ->setParameter($parameter, $value)
                ;
            }
        }
    }
110361
public function registerCriteriaFunction($criteria) {

        $id = \uniqid('criteria');

        if (\is_callable($criteria)) {
           $this->document_criterias[$id] = $criteria;
           return $id;
        }

        if (is_array($criteria)) {

            $fn = null;

            eval('$fn = function($document) { return '.UtilArrayQuery::buildCondition($criteria).'; };');

            $this->document_criterias[$id] = $fn;

            return $id;
        }

        return null;
    }
890037
private function expandCriteriaParameters(Criteria $criteria)
    {
        $expression = $criteria->getWhereExpression();

        if ($expression === null) {
            return [];
        }

        $valueVisitor = new SqlValueVisitor();

        $valueVisitor->dispatch($expression);

        [, $types] = $valueVisitor->getParamsAndTypes();

        return $types;
    }
856680
protected function applyCriteria(QueryBuilder $queryBuilder, array $criteria = null)
    {
        if (null === $criteria) {
            return;
        }

        foreach ($criteria as $property => $value) {
            if (null === $value) {
                $queryBuilder
                    ->andWhere($queryBuilder->expr()->isNull($this->getPropertyName($property)));
            } elseif (!is_array($value)) {
                $queryBuilder
                    ->andWhere($queryBuilder->expr()->eq($this->getPropertyName($property), ':' . $property))
                    ->setParameter($property, $value);
            } else {
                $queryBuilder->andWhere($queryBuilder->expr()->in($this->getPropertyName($property), $value));
            }
        }
    }
315339
private function makeQueryString($query = array())
	{
		$subject = $query[0];
		$operator = $query[1];
		$operand = $query[2];

		switch ($operator)
		{
			case '=':
				$string = $subject . ':' . $operand;
			break;
		}

		return $string;
	}
1364667
public function dump(Criteria $criteria)
    {
        $mode = strtoupper($criteria->getMode());

        $parts = array();
        foreach ($criteria as $criterium) {
            if ($criterium instanceof Criteria) {
                $parts[] = $this->dump($criterium, 1);
            } elseif ($criterium instanceof Criterium) {
                $type = $criterium->getType();
                $value = $criterium->getValue();
                if ($value instanceof \DateTime) {
                    $parts[] = $type.' = "'.$value->format('Y-m-d H:i:s').'"';
                } else {
                    $parts[] = $type.' = "'.$value.'"';
                }
            }
        }

        return '('.implode(' '.$mode.' ', $parts).')';
    }
168619
private function parseCriteria(array $criteria)
    {
        $out = '';
        if (!empty($criteria)) {
            $conditions = [];
            foreach ($criteria as $field => $value) {
                if (is_array($value)) {
                    $values = array_map(function($value) { return $this->connection->quote($value); }, $value);
                    $conditions[] = sprintf('%s IN (%s)', $field, implode(', ', $values));
                } else {
                    $operator = '=';
                    $ops = ['<>', '<', '>', '<=', '>='];
                    foreach ($ops as $op) {
                        if (false !== strpos($value, $op)) {
                            $operator = $op;
                            $value = str_replace(sprintf('%s ', $op), '', $value);
                            break;
                        }
                    }
                    $conditions[] = sprintf('%s %s %s', $field, $operator, $this->connection->quote($value));
                }
            }
            $out = sprintf(' WHERE %s', implode(' AND ', $conditions));
        }
        return $out;
    }
637725
protected function getNamePattern(array $criteria, string $extension): string
    {
        $names = [];

        $names[] = array_map(function ($criterion) use ($extension) {
            $uriExtension = URIHelper::containsExtension($criterion);
            if (! empty($extension)) {
                $extension = ltrim($extension, '.');

                if ($uriExtension === $extension) {
                    $criterion = substr($criterion,0,-strlen(".{$extension}"));
                }
            } else {
                $extension = URIHelper::containsExtension($criterion);
                if (!empty($extension)) {
                    $criterion = substr($criterion,0,-strlen(".{$extension}"));
                }
            }

            $criterion = preg_quote(URIHelper::getFilename($criterion), chr(1));

            return (empty($extension) || URIHelper::hasExtension($criterion, $extension))
                ? "{$criterion}(?:\..*?)$"
                : "{$criterion}\.{$extension}$";
        }, $criteria)[0];

        return chr(1) . implode('|', array_unique($names)) . chr(1);
    }
462466
public function delete(string $table, array $criteria = []): int {
		
		// this one is like the insertSingle above in that it uses its parameters
		// to build a query.  unlike that one, we execute it here and return the
		// number of deleted rows.
		
		$statement = "DELETE FROM $table";
		
		if (sizeof($criteria) > 0) {
			
			// we want to take our column names and turn them into a string
			// like x=? AND y=? AND z=? so that we can tack it onto our
			// $statement
			
			$columns = array_keys($criteria);
			array_walk($columns, function(&$x) {
				$x = sprintf("%s%s%s = ?", $this->columnPrefix, $x, $this->columnSuffix);
			});
			$statement .= " WHERE " . join(" AND ", $columns);
		}
		
		$bindings = array_values($criteria);
		
		try {
			return $this->dbConn->fetchAffected($statement, $bindings);
		} catch (\PDOException $pdoException) {
			throw $this->prepareDatabaseException($pdoException, $statement, $bindings);
		}
	}
150206
private function applyCriteriaToQueryBuilder(array $criteria, QueryBuilder $qb)
    {
        foreach ($criteria as $key => $value) {
            if (in_array($key, ['treeId', 'teaserId', 'eid', 'version'])) {
                $qb->andWhere($qb->expr()->eq("h.$key", $value));
            } elseif (in_array($key, ['language', 'action'])) {
                $qb->andWhere($qb->expr()->eq("h.$key", $qb->expr()->literal($value)));
            } elseif (in_array($key, ['comment'])) {
                $qb->andWhere($qb->expr()->like("h.$key", $qb->expr()->literal("%$value%")));
            } else {
                throw new InvalidArgumentException("Unkown field $key");
            }
        }
    }
514576
public function prepareCriteria($criteria)
    {
        if (is_null($criteria)) {
            $criteria = array();
        }

        if (array_key_exists('$id', $criteria)) {
            $criteria['id'] = $criteria['$id'];
            unset($criteria['$id']);
        }

        return $criteria ? : array();
    }
770782
protected function applyCriteria($criteria)
    {
        $query = $this->getQuery();
        $metadata = $this->getEntityMetadata();
        
        if (null !== $criteria) {
            switch (true) {
                case is_scalar($criteria):
                    $identifier = $metadata->getRawSQLName($metadata->getIdentifier());
                    $query->addConditions($identifier, $criteria);
                    break;
                
                case $criteria instanceof QueryBuilder\Select:
                    $criteria->setFromTable($metadata->getTableName());
                    $this->setQuery($criteria);
                    break;
                
                case (is_array($criteria) and count($criteria) > 0):
                    $query->addConditions(...$criteria);
                    break;
                
                default:
                    throw new NotSupportedException('It is impossible to determine the correct assignment criteria');
                    break;
            }
        }
        
        return $this;
    }