<?php
namespace App\Services\Search;
use App\Services\Search\BaseSearch;
use App\Entity\Post;
use \DateTime;
use App\Cache\Helper as CacheHelper;
class SearchPost extends BaseSearch
{
public function get($aOptions)
{
$default_options = [
'ids_collection' => false,
'sorting' => 'name',
'aStatus' => [
Post::STATUS_INIT,
Post::STATUS_READY,
Post::STATUS_WAITING,
],
'max_results' => false,
'page' => 1,
'aExcluded_ids' => false,
//'show_hidden' => false,
'show_pagination' => false,
'return_count' => false // if true, will only return the count instead of the rows
];
$aOptions = $this->getOptions($default_options, $aOptions);
$alias = '_'.uniqid();
$qb = $this->em->createQueryBuilder();
if($aOptions['return_count'])
{
$qb->select($qb->expr()->countDistinct($alias.'.id'));
} else {
$qb->select('DISTINCT '.$alias.'.id');
}
$qb->from(Post::class, $alias);
// Static collection of IDs
if(is_array($aOptions['ids_collection']))
{
if(empty($aOptions['ids_collection']))
{
// 'ids_collection' rules over any other entry; if it comes empty, show empty results
return [
'results' => [],
'pagination' => false
];
} else {
$qb->andWhere(
$qb->expr()->in($alias.'.id', $aOptions['ids_collection'])
);
}
}
if(!empty($aOptions['aExcluded_ids']))
{
$qb->andWhere(
$qb->expr()->notIn($alias.'.id', $aOptions['aExcluded_ids'])
);
}
if($aOptions['aStatus'])
{
$qb->andWhere(
$qb->expr()->in($alias.'.status', $aOptions['aStatus'])
);
}
switch($aOptions['sorting'])
{
case 'date':
$qb->orderBy($alias.'.publish_date','DESC');
break;
case 'field': // preserve order set in 'ids_collection' param
if(is_array($aOptions['ids_collection']) && !empty($aOptions['ids_collection']))
{
$qb
->addSelect("FIELD(".$alias.".id, ".implode(', ', $aOptions['ids_collection']).") AS HIDDEN sorting")
->orderBy('sorting', 'ASC');
}
break;
case 'name':
$qb->orderBy($alias.'.name','ASC');
break;
case 'random': // expensive query
$qb
->addSelect("RAND() AS HIDDEN random_value")
->orderBy('random_value', 'ASC');
break;
}
$query = $qb->getQuery();
/*if(!$aOptions['show_pagination'] && $aOptions['max_results'])
{
$query->setMaxResults($aOptions['max_results']);
}*/
$resultCache_id = CacheHelper::fixId(Post::class).'_collection_'.md5($query->getSQL());
$resultCache_ttl = 604800;
if(!$aOptions['no_cache'])
{
$query
->useQueryCache(true)
->setResultCacheLifetime($resultCache_ttl)
->setResultCacheId($resultCache_id);
}
return $aOptions['return_count'] ? [
'results' => $query->getSingleScalarResult(),
'pagination' => false
] : $this->paginate([
'aResults' => $query->getArrayResult(),
'repository_class' => Post::class,
'max_results' => $aOptions['max_results'],
'page' => $aOptions['page'],
'show_pagination' => $aOptions['show_pagination'],
'paginator_params' => $aOptions['paginator_params'],
'paginator_route' => $aOptions['paginator_route']
]);
}
}