<?php
namespace App\Repository;
use App\Entity\NotificationReceipt;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\NoResultException;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<NotificationReceipt>
*
* @method NotificationReceipt|null find($id, $lockMode = null, $lockVersion = null)
* @method NotificationReceipt|null findOneBy(array $criteria, array $orderBy = null)
* @method NotificationReceipt[] findAll()
* @method NotificationReceipt[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class NotificationReceiptRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, NotificationReceipt::class);
}
public function add(NotificationReceipt $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(NotificationReceipt $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function getUnreadNotificationsCount(User $user): int
{
$alias = 'notification_receipt';
$queryBuilder = $this->createQueryBuilder($alias);
$queryBuilder
->select('count('.$alias.'.id)')
->andWhere($alias.'.user = :user')
->andWhere($queryBuilder->expr()->isNull($alias.'.readAt'))
->setParameter('user', $user)
;
try {
return $queryBuilder->getQuery()->getSingleScalarResult();
} catch (NoResultException|NonUniqueResultException $e) {
return 0;
}
}
}