<?php
namespace Roothirsch\NotificationBundle\Controller;
use Doctrine\ORM\EntityManagerInterface;
use Roothirsch\DamBundle\Entity\Category;
use Roothirsch\DamBundle\Repository\CategoryRepository;
use Roothirsch\NotificationBundle\Entity\NotificationReadOn;
use Roothirsch\NotificationBundle\Repository\NotificationReadOnRepository;
use Roothirsch\NotificationBundle\Repository\NotificationRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\SerializerInterface;
/**
* @Route("/api/notifications", name="api_notifications_")
*/
class FetchController extends AbstractController
{
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
/**
* @var NotificationRepository
*/
private $notificationRepository;
/**
* @var EntityManagerInterface
*/
private $entityManager;
/**
* @var NotificationReadOnRepository
*/
private $readOnRepository;
/** @var SerializerInterface */
private $serializer;
/**
* @param TokenStorageInterface $tokenStorage
* @param NotificationRepository $notificationRepository
* @param EntityManagerInterface $entityManager
* @param NotificationReadOnRepository $readOnRepository
*/
public function __construct(TokenStorageInterface $tokenStorage, NotificationRepository $notificationRepository, EntityManagerInterface $entityManager, NotificationReadOnRepository $readOnRepository, SerializerInterface $serializer)
{
$this->tokenStorage = $tokenStorage;
$this->notificationRepository = $notificationRepository;
$this->entityManager = $entityManager;
$this->readOnRepository = $readOnRepository;
$this->serializer = $serializer;
}
/**
* @Route("/unread", name="read", methods={"GET"})
*/
public function read()
{
$readOn = $this->readOnRepository->findOneBy(["user" => $this->tokenStorage->getToken()->getUser()]);
if(!$readOn) {
$readOn = new NotificationReadOn();
$readOn->setDate(new \DateTime());
}
$unread = $this->notificationRepository->findUnreadNotifications($readOn);
$read = $this->notificationRepository->findReadNotifications($readOn);
return new JsonResponse([
'read' => json_decode($this->serializer->serialize($read, 'json'), TRUE),
'unread' => json_decode($this->serializer->serialize($unread, 'json'), TRUE)
]);
}
/**
* @Route("/read", name="check", methods={"POST"})
*/
public function check()
{
$user = $this->tokenStorage->getToken()->getUser();
/** @var NotificationReadOn $readOne */
$readOne = $this->readOnRepository->findOneBy([
"user" => $user
]);
if(!$readOne){
$readOne = new NotificationReadOn();
$readOne->setUser($user);
}
$readOne->setDate(new \DateTime());
$this->entityManager->persist($readOne);
$this->entityManager->flush();
return $readOne;
}
}