<?php
namespace App\EventSubscriber;
use CalendarBundle\Entity\Event;
use CalendarBundle\CalendarEvents;
use App\Repository\AgendaRepository;
use App\Repository\TaskRepository;
use CalendarBundle\Event\CalendarEvent;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CalendarSubscriber implements EventSubscriberInterface
{
private $taskRepository;
private $security;
private $router;
public const TASK_VISIBILITY = 'Public';
public function __construct(TaskRepository $taskRepository, Security $security, UrlGeneratorInterface $router)
{
$this->taskRepository = $taskRepository;
$this->security = $security;
$this->router = $router;
}
public static function getSubscribedEvents()
{
return [
CalendarEvents::SET_DATA => 'onCalendarSetData',
];
}
public function onCalendarSetData(CalendarEvent $calendar)
{
$start = $calendar->getStart();
$end = $calendar->getEnd();
$filters = $calendar->getFilters();
// You may want to make a custom query from your database to fill the calendar
$tasks = $this->taskRepository
->createQueryBuilder('t')
->leftJoin('t.participants', 'p')
->addSelect('p')
//->where('(t.begin_at BETWEEN :start and :end OR t.end_at BETWEEN :start and :end) and t.created_by = :created_by')
->where('t.begin_at BETWEEN :start and :end OR t.end_at BETWEEN :start and :end')
->setParameter('start', $start->format('Y-m-d H:i:s'))
->setParameter('end', $end->format('Y-m-d H:i:s'))
//->setParameter('created_by', $this->security->getUser())
->getQuery()
->getResult()
;
foreach ($tasks as $task) {
if (($task->getVisibiity() == self::TASK_VISIBILITY) or ($task->getCreatedBy()->getUsername() == $this->security->getUser()->getUsername() or $task->isUserParticipated($this->security->getUser()))) {
$taskEvent = new Event(
$task->getTitle(),
$task->getBeginAt(),
$task->getEndAt()
);
$taskEvent->setOptions([
'backgroundColor' => $task->getColor(),
'borderColor' => '#d3dde2',
]);
$taskEvent->addOption(
'url',
$this->router->generate('task_edit', [
'id' => $task->getId(),
])
);
// finally, add the event to the CalendarEvent to fill the calendar
$calendar->addEvent($taskEvent);
}
}
}
}