Last active
May 7, 2024 12:04
-
-
Save galiazzi/5e5f04f9753ba4d8a9b972c87dc2a805 to your computer and use it in GitHub Desktop.
Doctrine DQL cast function
This file contains 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 | |
use Doctrine\ORM\Query\AST\Functions\FunctionNode; | |
use Doctrine\ORM\Query\Lexer; | |
use Doctrine\ORM\Query\Parser; | |
use Doctrine\ORM\Query\SqlWalker; | |
class Cast extends FunctionNode | |
{ | |
private $expr1; | |
private $expr2; | |
public function parse(Parser $parser) | |
{ | |
$parser->match(Lexer::T_IDENTIFIER); | |
$parser->match(Lexer::T_OPEN_PARENTHESIS); | |
$this->expr1 = $parser->ArithmeticExpression(); | |
$parser->match(Lexer::T_COMMA); | |
$this->expr2 = $parser->StringPrimary(); | |
$parser->match(Lexer::T_CLOSE_PARENTHESIS); | |
} | |
public function getSql(SqlWalker $sqlWalker) | |
{ | |
$type = trim($this->expr2->dispatch($sqlWalker), "'"); | |
return sprintf( | |
'cast(%s as %s)', | |
$this->expr1->dispatch($sqlWalker), | |
$type | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For the record, it's better to use
If you don't do that, doctrine will not replace potential alias in the select clause.
IE: without this patch, such code does not work
because the
parameterName
in the cast is not replaced