Skip to content

Instantly share code, notes, and snippets.

@tonydub
Forked from instabledesign/Greatest.php
Created January 12, 2017 15:49
Show Gist options
  • Save tonydub/2eec3d1054733384976b192db5113b46 to your computer and use it in GitHub Desktop.
Save tonydub/2eec3d1054733384976b192db5113b46 to your computer and use it in GitHub Desktop.
Doctrine ORM Function GREATEST
#app/config.yml
doctrine:
orm:
dql:
string_functions:
greatest: AppBundle\Doctrine\ORM\Functions\Greatest
#src/AppBundle/Doctrine/ORM/Functions/Greatest.php
<?php
namespace AppBundle\Doctrine\ORM\Functions;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\AST\PathExpression;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
class Greatest extends FunctionNode {
/**
* @var array
*/
protected $greatestArgs;
/**
* @param SqlWalker $sqlWalker
*
* @return string
*/
public function getSql(SqlWalker $sqlWalker)
{
return sprintf('GREATEST(%s)',
implode(', ', array_map(
function(PathExpression $expression) use($sqlWalker) {
return $expression->dispatch($sqlWalker);
},
$this->greatestArgs
))
);
}
/**
* @param Parser $parser
*/
public function parse(Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
// 2 arguments minimum
$this->greatestArgs[] = $parser->ArithmeticPrimary();
$parser->match(Lexer::T_COMMA);
$this->greatestArgs[] = $parser->ArithmeticPrimary();
while ($parser->getLexer()->isNextToken(Lexer::T_COMMA)) {
$parser->match(Lexer::T_COMMA);
$this->greatestArgs[] = $parser->ArithmeticPrimary();
}
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment