Skip to content

Instantly share code, notes, and snippets.

@daum
Last active July 9, 2019 09:40
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save daum/6dba57f690aff49b60535ba3a723d411 to your computer and use it in GitHub Desktop.
Save daum/6dba57f690aff49b60535ba3a723d411 to your computer and use it in GitHub Desktop.
<?php
namespace Example\Doctrine\Util;
use Doctrine\ORM\Query;
class QueryUtils
{
/**
* @param Query $query
* @return array An array with 3 indexes, sql the SQL statement with parameters as ?, params the ordered parameters, and paramTypes as the types each parameter is.
*/
public static function getRunnableQueryAndParametersForQuery(Query $query)
{
$sql = $query->getSQL();
$c = new \ReflectionClass('Doctrine\ORM\Query');
$parser = $c->getProperty('_parserResult');
$parser->setAccessible(true);
/** @var \Doctrine\ORM\Query\ParserResult $parser */
$parser = $parser->getValue($query);
$resultSet = $parser->getResultSetMapping();
// Change the aliases back to what was originally specified in the QueryBuilder.
$sql = preg_replace_callback('/AS\s([a-zA-Z0-9_]+)/',function($matches) use($resultSet) {
$ret = 'AS ';
if($resultSet->isScalarResult($matches[1]))
$ret.=$resultSet->getScalarAlias($matches[1]);
else
$ret.=$matches[1];
return $ret;
},$sql);
$m = $c->getMethod('processParameterMappings');
$m->setAccessible(true);
list($params,$types)= $m->invoke($query,$parser->getParameterMappings());
return ['sql' => $sql, 'params' => $params,'paramTypes' => $types];
}
}
<?php
// Example Usage
// Get a Query Builder
$qb = $this->getDoctrine()
->getRepository('AppBundle:Example')
->getQueryBuilderForParams($params);
$queryInfo = QueryUtils::getRunnableQueryAndParametersForQuery($qb->getQuery());
// Use the query to insert to a temp table.
$this->getDoctrine()
->getManager('default')
->getConnection()
->executeQuery("INSERT INTO my_temp_table (col1,col2,col3,col4) ".$queryInfo['sql'],
$queryInfo['params'],
$queryInfo['paramTypes']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment