<?php
namespace Aqarmap\Bundle\ListingBundle\Repository;
use Aqarmap\Bundle\ListingBundle\Document\ListingImpression;
use Doctrine\Bundle\MongoDBBundle\ManagerRegistry;
use Doctrine\Bundle\MongoDBBundle\Repository\ServiceDocumentRepository;
use Doctrine\ODM\MongoDB\Aggregation\Builder;
class ListingImpressionRepository extends ServiceDocumentRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, ListingImpression::class);
}
public function countListingsTotalImpressions($criteria)
{
$qb = $this->createQueryBuilder();
$qb->count()
->addAnd($qb->expr()->field('listingId')->in($criteria['listingIds']));
if (isset($criteria['start_date'])) {
$startDate = new \DateTime($criteria['start_date']);
$qb->addAnd($qb->expr()->field('createdAt')->gte($startDate));
}
if (isset($criteria['end_date'])) {
$endDate = new \DateTime($criteria['end_date']);
$qb->addAnd($qb->expr()->field('createdAt')->lte($endDate->modify('+1 day')));
}
if (!empty($criteria['start_date']) && !empty($criteria['end_date'])) {
$startDate = new \DateTime($criteria['start_date']);
$qb->addAnd($qb->expr()->field('createdAt')->gte($startDate))
->addAnd($qb->expr()->field('createdAt')->lte($endDate->modify('+1 day')));
}
return $qb->getQuery()->execute();
}
/**
* @return object|null
*/
public function getLastImpression()
{
return $this->createQueryBuilder()
->sort('id', 'desc')
->limit(1)
->getQuery()
->getSingleResult();
}
/**
* Get listings with total impressions between two ids.
*
* @return Builder
*
* @throws \Exception
*/
public function search(array $criteria)
{
$builder = $this->createAggregationBuilder();
if ($criteria['listingsIds'] ?? false) {
$builder->match()->field('listingId')->in($criteria['listingsIds']);
}
if ($criteria['startId'] ?? false) {
$builder->match()->field('_id')->gt($criteria['startId']);
}
if ($criteria['endId'] ?? false) {
$builder->match()->field('_id')->lte($criteria['endId']);
}
if (!empty($criteria['startDate'])) {
$startDate = $criteria['startDate'];
if (!$startDate instanceof \DateTime) {
$startDate = new \DateTime($startDate);
}
$builder->match()->field('createdAt')->gte($startDate);
}
if (!empty($criteria['endDate'])) {
$endDate = $criteria['endDate'];
if (!$endDate instanceof \DateTime) {
$endDate = new \DateTime($endDate);
}
$builder->match()->field('createdAt')->lte($endDate->modify('+1 day'));
}
if (!empty($criteria['groupByWithCount'])) {
$builder->group()
->field('_id')
->expression($criteria['groupByWithCount'])
->field('count')
->expression($builder->expr()->sum(1));
}
if ($criteria['limit'] ?? false) {
$builder->limit($criteria['limit']);
}
return $builder;
}
}