<?php
namespace ERP\TaskBundle\EventSubscriber;
use ApiPlatform\Core\Api\IriConverterInterface;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Eav\AttributeValue;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use ERP\MeetingNoteBundle\Entity\MeetingNote;
use ERP\TaskBundle\Entity\Task;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Workflow\Registry;
class ActionableMeetingNoteCreatedSubscriber implements EventSubscriberInterface
{
/**
* @var Registry
*/
private $registry;
/**
* @var EntityManagerInterface
*/
private $entityManager;
/**
* @var IriConverterInterface
*/
private $iriConverter;
public function __construct(Registry $registry, EntityManagerInterface $entityManager, IriConverterInterface $iriConverter)
{
$this->registry = $registry;
$this->entityManager = $entityManager;
$this->iriConverter = $iriConverter;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['taskCreated', EventPriorities::POST_WRITE],
];
}
public function taskCreated(ViewEvent $event): void
{
$meetingNote = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$meetingNote instanceof MeetingNote || Request::METHOD_POST !== $method) {
return;
}
/** @var AttributeValue $actionable */
if (null === ($actionable = $meetingNote->getAttributeValueByName('actionable')) || true !== $actionable->getValue()) {
return;
}
/** @var AttributeValue $assigneeValue */
if (null === ($assigneeValue = $meetingNote->getAttributeValueByName('assignee'))) {
return;
}
/** @var User $assignee */
$assignee = $this->iriConverter->getItemFromIri($assigneeValue->getValue());
if (null === ($dueDate = $meetingNote->getAttributeValueByName('due_date'))) {
return;
}
$task = new Task();
$task->setOwner($meetingNote->getUser());
$task->setAssignee($assignee);
$task->setDueDate(new \DateTime($dueDate->getValue()));
$task->setTitle($meetingNote->getMeeting()->getTitle());
$task->setDescription($meetingNote->getContent());
$this->entityManager->persist($task);
$this->entityManager->flush();
}
}