<?php
declare(strict_types=1);
namespace Slivki\Repository\Comment;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\Persistence\ManagerRegistry;
use Slivki\Entity\City;
use Slivki\Entity\Comment;
use Slivki\Entity\Offer;
use Slivki\Exception\Comment\CommentNotFountException;
final class CommentRepository extends ServiceEntityRepository implements CommentRepositoryInterface
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Comment::class);
}
public function getById(int $id): Comment
{
$comment = $this->findById($id);
if (!$comment instanceof Comment) {
throw new CommentNotFountException();
}
return $comment;
}
public function findById(int $id): ?Comment
{
$qb = $this->createQueryBuilder('c');
$expr = $qb->expr();
return $qb
->andWhere($expr->eq('c.ID', ':id'))
->setParameters([
'id' => $id,
])
->getQuery()
->getOneOrNullResult();
}
public function getLastOfferComments(int $limit): array
{
$qb = $this->createQueryBuilder('comment');
$expr = $qb->expr();
return $qb
->innerJoin(Offer::class, 'offer', Join::WITH, $expr->eq('offer.ID', 'comment.entityID'))
->andWhere($expr->eq('comment.hidden', ':hidden'))
->andWhere($expr->eq('comment.confirmedPhone', ':confirmedPhone'))
->andWhere($expr->neq('offer.defaultCity', ':tashkentCityId'))
->setParameters([
'hidden' => false,
'confirmedPhone' => true,
'tashkentCityId' => City::TASHKENT_CITY_ID,
])
->addOrderBy($expr->desc('comment.createdOn'))
->setMaxResults($limit)
->getQuery()
->getResult();
}
public function getOfferCommentByIdAndOfferDirector(int $commentId, int $offerDirectorId): Comment
{
$qb = $this->createQueryBuilder('comment');
$expr = $qb->expr();
$comment = $qb
->innerJoin(Offer::class, 'offer', Join::WITH, $expr->eq('offer.ID', 'comment.entityID'))
->innerJoin('offer.directors', 'director')
->andWhere($expr->eq('comment.ID', ':commentId'))
->andWhere($expr->eq('director', ':directorId'))
->setParameters([
'commentId' => $commentId,
'directorId' => $offerDirectorId,
])
->getQuery()
->getOneOrNullResult();
if (!$comment instanceof Comment) {
throw new CommentNotFountException();
}
return $comment;
}
public function save(Comment $comment): void
{
$entityManager = $this->getEntityManager();
$entityManager->persist($comment);
$entityManager->flush($comment);
}
}