<?php
namespace App\EventSubscriber;
use App\Repository\BookingRepository;
use CalendarBundle\CalendarEvents;
use CalendarBundle\Entity\Event;
use CalendarBundle\Event\CalendarEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class CalendarSubscriber implements EventSubscriberInterface
{
private $bookingRepository;
private $router;
private $token;
private $user;
private $role;
public function __construct(TokenStorageInterface $token, BookingRepository $bookingRepository, UrlGeneratorInterface $router)
{
$this->token = $token;
$this->user = $this->token->getToken()->getUser();
$this->role = $this->user->getRoles();
$this->bookingRepository = $bookingRepository;
$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();
$strRole = '%' . $this->role[0] . '%';
// Modify the query to fit to your entity and needs
// Change booking.beginAt by your start date property
$bookings = $this->bookingRepository
->createQueryBuilder('booking')
->innerJoin('booking.user', 'u')
->where('booking.beginAt BETWEEN :start and :end OR booking.endAt BETWEEN :start and :end')
->andWhere('u.roles LIKE :role')
->setParameter('start', $start->format('Y-m-d H:i:s'))
->setParameter('end', $end->format('Y-m-d H:i:s'))
->setParameter('role', $strRole)
->getQuery()
->getResult();
foreach ($bookings as $booking) {
// this create the events with your data (here booking data) to fill calendar
$bookingEvent = new Event(
$booking->getTitle(),
$booking->getBeginAt(),
$booking->getEndAt() // If the end date is null or not defined, a all day event is created.
);
/*
* Add custom options to events
*
* For more information see: https://fullcalendar.io/docs/event-object
* and: https://github.com/fullcalendar/fullcalendar/blob/master/src/core/options.ts
*/
$bookingEvent->setOptions([
'backgroundColor' => 'blue',
'borderColor' => 'blue',
]);
$bookingEvent->addOption(
'url',
$this->router->generate('app_booking_show', [
'id' => $booking->getId(),
])
);
// finally, add the event to the CalendarEvent to fill the calendar
$calendar->addEvent($bookingEvent);
}
}
}