Last active
August 29, 2015 14:11
-
-
Save fabiopaiva/93252c0a2a7f16a96109 to your computer and use it in GitHub Desktop.
ZF2 + Doctrine Custom Function Mysql DateDiff
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 | |
namespace Application\DoctrineFunction; | |
use Doctrine\ORM\Query\Lexer; | |
use Doctrine\ORM\Query\AST\Functions\FunctionNode; | |
class DateDiff extends FunctionNode { | |
/* | |
* holds the timestamp of the DATE_FORMAT DQL statement | |
* @var mixed | |
*/ | |
protected $dateInit; | |
/** | |
* holds the '%format' parameter of the DATE_FORMAT DQL statement | |
* @var string | |
*/ | |
protected $dateEnd; | |
/** | |
* getSql - allows ORM to inject a DATE_FORMAT() statement into an SQL string being constructed | |
* @param \Doctrine\ORM\Query\SqlWalker $sqlWalker | |
* @return void | |
*/ | |
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { | |
return 'DATEDIFF(' . | |
$sqlWalker->walkArithmeticExpression($this->dateInit) . | |
',' . | |
$sqlWalker->walkStringPrimary($this->dateEnd) . | |
')'; | |
} | |
/** | |
* parse - allows DQL to breakdown the DQL string into a processable structure | |
* @param \Doctrine\ORM\Query\Parser $parser | |
*/ | |
public function parse(\Doctrine\ORM\Query\Parser $parser) { | |
$parser->match(Lexer::T_IDENTIFIER); | |
$parser->match(Lexer::T_OPEN_PARENTHESIS); | |
$this->dateInit = $parser->ArithmeticExpression(); | |
$parser->match(Lexer::T_COMMA); | |
$this->dateEnd = $parser->StringPrimary(); | |
$parser->match(Lexer::T_CLOSE_PARENTHESIS); | |
} | |
} |
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 | |
return array( | |
'doctrine' => array( | |
'configuration' => array( | |
'orm_default' => array( | |
'datetime_functions' => array( | |
'DATEDIFF' => 'Application\DoctrineFunction\DateDiff', | |
) | |
) | |
), | |
); |
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 | |
namespace Application\Controller; | |
class MyController{ | |
public function indexAction(){ | |
$qb = $this | |
->getOM() | |
->getRepository('Application\Entity\MyEntity') | |
->createQueryBuilder('q') | |
$qb->select(array('DATEDIFF(q.date1, q.date2) as diff')); | |
$result = $qb->getQuery()->getResult(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment