Doctrine:如何添加带有可选参数的自定义函数?

Oli*_*ons 5 php symfony doctrine-orm

在官方解释之后,我想创建我的自定义MySQL函数ROUND(),它可以采用(非强制性的)另一个第二个参数.

我已经完成了这个:

<?php
namespace HQF\Bundle\PizzasBundle\DQL;

use \Doctrine\ORM\Query\AST\Functions\FunctionNode;
use \Doctrine\ORM\Query\Lexer;

class MysqlRound extends FunctionNode
{
    public $simpleArithmeticExpression;

    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
    {
        return 'ROUND(' . $sqlWalker->walkSimpleArithmeticExpression(
            $this->simpleArithmeticExpression
        ) . ')';
    }

    public function parse(\Doctrine\ORM\Query\Parser $parser)
    {
        $lexer = $parser->getLexer();

        $parser->match(Lexer::T_IDENTIFIER);
        $parser->match(Lexer::T_OPEN_PARENTHESIS);

        $this->simpleArithmeticExpression = $parser->SimpleArithmeticExpression();

        $parser->match(Lexer::T_CLOSE_PARENTHESIS);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是如何实现ROUND(XX)好的事实,ROUND(XX, YY)也可以呢?

Mic*_*ick 11

你需要声明第二个参数,并使用Lexer如下:

namespace HQF\Bundle\PizzasBundle\DQL;

use \Doctrine\ORM\Query\AST\Functions\FunctionNode;
use \Doctrine\ORM\Query\Lexer;

class MysqlRound extends FunctionNode
{
    private $firstExpression = null;
    private $secondExpression = null;

    public function parse(\Doctrine\ORM\Query\Parser $parser)
    {
        $lexer = $parser->getLexer();
        $parser->match(Lexer::T_IDENTIFIER);
        $parser->match(Lexer::T_OPEN_PARENTHESIS);
        $this->firstExpression = $parser->ArithmeticPrimary();

        // parse second parameter if available
        if(Lexer::T_COMMA === $lexer->lookahead['type']){
            $parser->match(Lexer::T_COMMA);
            $this->secondExpression = $parser->ArithmeticPrimary();
        }

        $parser->match(Lexer::T_CLOSE_PARENTHESIS);
    }

    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
    {
        // use second parameter if parsed
        if (null !== $this->secondExpression){
            return 'ROUND(' 
                . $this->firstExpression->dispatch($sqlWalker)
                . ', '
                . $this->secondExpression->dispatch($sqlWalker)
                . ')';
        }

        return 'ROUND(' . $this->firstExpression->dispatch($sqlWalker) . ')';
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

这里编写了许多Doctrine2扩展.所有归功于@beberlei的伟大作品.有很多功能可(IFELSE,IFNULL,NULLIF,COS,ACOS,等...),但不是他们的全部(ROUND,GREATEST或LEAST失踪,但你仍然可以自己写他们,如果你需要他们.)