<?php
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\SqlWalker;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\Lexer;
use PHPSnippets\Db\Entity\Test;
class ReplaceFunction extends FunctionNode
{
private $str;
private $from;
private $to;
public function getSql(SqlWalker $sqlWalker)
{
return 'REPLACE(' .
$this->str->dispatch($sqlWalker) . ', ' .
$this->from->dispatch($sqlWalker) . ', ' .
$this->to->dispatch($sqlWalker) .
')';
}
public function parse(Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->str = $parser->StringPrimary();
$parser->match(Lexer::T_COMMA);
$this->from = $parser->StringPrimary();
$parser->match(Lexer::T_COMMA);
$this->to = $parser->StringPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
}
// make ReplaceFunction available
$entityManager->getConfiguration()
->addCustomStringFunction('REPLACE', ReplaceFunction::CLASS);
$results = $entityManager->createQuery('SELECT t.name, REPLACE(t.name, \'test\', \'BAZ\') replaced FROM ' . Test::CLASS . ' t')
->getResult();
foreach ($results as $result) {
echo sprintf('%s replaced to %s', $result['name'], $result['replaced']) . PHP_EOL;
}