Skip to content

Instantly share code, notes, and snippets.

@lethak
Last active August 29, 2015 14:15
Show Gist options
  • Save lethak/9edc56d75712b87d0f77 to your computer and use it in GitHub Desktop.
Save lethak/9edc56d75712b87d0f77 to your computer and use it in GitHub Desktop.
Adding seconds to a DateTime object in doctrine2 DQL
<?php
// in symfony2 app/ config.yml ...
doctrine:
orm:
entity_managers:
default:
dql:
datetime_functions:
unix_timestamp: Acme\AcmeBundle\DoctrineExtension\ORM\Query\AST\Functions\UnixTimestamp
// THEN, In a custom doctrine function file
//... SiteBundle\DoctrineExtension\ORM\Query\AST\Functions\UnixTimestamp.php
namespace Acme\AcmeBundle\DoctrineExtension\ORM\Query\AST\Functions;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\SqlWalker;
use Doctrine\ORM\Query\Parser;
/**
* UnixTimestampFunction ::= "UNIXTIMESTAMP" "(" ArithmeticPrimary ")"
*/
class UnixTimestamp extends \Doctrine\ORM\Query\AST\Functions\FunctionNode
{
public $firstDateExpression = null;
public function parse(Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER); // (2)
$parser->match(Lexer::T_OPEN_PARENTHESIS); // (3)
$this->firstDateExpression = $parser->ArithmeticPrimary(); // (4)
$parser->match(Lexer::T_CLOSE_PARENTHESIS); // (3)
}
public function getSql(SqlWalker $sqlWalker)
{
return 'UNIX_TIMESTAMP(' .
$this->firstDateExpression->dispatch($sqlWalker).
')'; // (7)
}
}
/// THEN, In your controller/Repository..
$now = new \DateTime("now",new \DateTimeZone('UTC'));
$QB = $this->createQueryBuilder('h');
$Query = $QB->where('h.dateLastCrawled IS NULL')
->orWhere($QB->expr()->sum( "UNIX_TIMESTAMP(h.dateLastCrawled)", 'h.revisitAfterSeconds')." <= UNIX_TIMESTAMP(:now)")
->setParameter(':now', $now)
->orderBy('h.revisitAfterSeconds', 'ASC')
->setFirstResult($batchOptions['offset'])
->setMaxResults($batchOptions['limit'])
->getQuery()
;
$result = $Query->getResult();
@lethak
Copy link
Author

lethak commented Feb 22, 2015

Updated the gist with a WORKING SOLUTION

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment