2021-03-29 13:58:05 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Repository\Blog;
|
|
|
|
|
|
|
|
use App\Entity\Blog\Post;
|
|
|
|
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
|
|
|
use Doctrine\Persistence\ManagerRegistry;
|
|
|
|
|
|
|
|
class PostRepository extends ServiceEntityRepository
|
|
|
|
{
|
|
|
|
public function __construct(ManagerRegistry $registry)
|
|
|
|
{
|
|
|
|
parent::__construct($registry, Post::class);
|
|
|
|
}
|
2021-03-29 22:45:51 +02:00
|
|
|
|
|
|
|
public function getEm()
|
|
|
|
{
|
|
|
|
return $this->getEntityManager();
|
|
|
|
}
|
2022-09-09 20:10:51 +02:00
|
|
|
|
|
|
|
public function findSimilarPosts(Post $post, int $quantity = 5): array
|
|
|
|
{
|
|
|
|
$query1 = $this->createQueryBuilder('p');
|
|
|
|
$query2 = $this->createQueryBuilder('p');
|
2022-09-10 11:45:58 +02:00
|
|
|
$categories = $post->getCategories()->getValues();
|
|
|
|
$tags = $post->getTags();
|
2022-09-09 20:10:51 +02:00
|
|
|
|
|
|
|
$query1->orderBy('p.publishedAt', 'DESC');
|
|
|
|
|
2022-09-10 11:45:58 +02:00
|
|
|
if (count($tags)) {
|
|
|
|
foreach ($tags as $k => $entity) {
|
|
|
|
$query1
|
|
|
|
->orWhere('p.tags LIKE :tag'.$k)
|
|
|
|
->setParameter(':tag'.$k, '%"'.$entity['label'].'"%')
|
|
|
|
;
|
|
|
|
}
|
|
|
|
|
|
|
|
$search1 = $query1->getQuery()->getResult();
|
|
|
|
} else {
|
|
|
|
$search1 = [];
|
|
|
|
}
|
|
|
|
|
|
|
|
if (count($categories)) {
|
|
|
|
$query2
|
|
|
|
->orderBy('p.publishedAt', 'DESC')
|
|
|
|
->andWhere('p.status = 1')
|
|
|
|
->join('p.categories', 'c')
|
|
|
|
->where('c.id IN (:ids)')
|
|
|
|
->setParameter(':ids', array_map(
|
|
|
|
fn ($e) => $e->getId(),
|
|
|
|
$categories
|
|
|
|
))
|
2022-09-09 20:10:51 +02:00
|
|
|
;
|
2022-09-10 11:45:58 +02:00
|
|
|
|
|
|
|
$search2 = $query2->getQuery()->getResult();
|
|
|
|
} else {
|
|
|
|
$search2 = [];
|
2022-09-09 20:10:51 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
$now = new \DateTime();
|
|
|
|
$posts = [];
|
|
|
|
|
|
|
|
foreach ([$search1, $search2] as $results) {
|
|
|
|
foreach ($results as $result) {
|
|
|
|
if (count($posts) === $quantity) {
|
|
|
|
continue 2;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($result->getId() === $post->getId()) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Post::DRAFT === $result->getStatus()) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (null === $result->getPublishedAt()) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2022-09-10 11:24:10 +02:00
|
|
|
if (null === $result->getImage()) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2022-09-09 20:10:51 +02:00
|
|
|
if ($result->getPublishedAt() > $now) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!isset($posts[$result->getId()])) {
|
|
|
|
$posts[$result->getId()] = $result;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $posts;
|
|
|
|
}
|
2021-03-29 13:58:05 +02:00
|
|
|
}
|