<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\DashboardWidget;
use App\Manager\DashboardWidgetManager;
use App\Manager\MissionManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\String\UnicodeString;
class DashboardWidgetSubscriber implements EventSubscriberInterface
{
private DashboardWidgetManager $dashboardWidgetManager;
private MissionManager $missionManager;
public function __construct(DashboardWidgetManager $dashboardWidgetManager, MissionManager $missionManager)
{
$this->dashboardWidgetManager = $dashboardWidgetManager;
$this->missionManager = $missionManager;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => [
['apiPreCreate', EventPriorities::PRE_WRITE],
['apiPreUpdate', EventPriorities::PRE_WRITE],
['apiPreDelete', EventPriorities::PRE_WRITE],
],
];
}
public function apiPreCreate(ViewEvent $event)
{
$dashboardWidget = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
$operation = $event->getRequest()->attributes->get('_api_item_operation_name');
if (!$this->isDashboardWidget($dashboardWidget) || $method !== Request::METHOD_POST || $operation === 'image_upload_put') {
return;
}
$dashboardWidget = $this->dashboardWidgetManager->checkTitle($dashboardWidget);
$this->preCreate($dashboardWidget);
}
public function preCreate(DashboardWidget $dashboardWidget)
{
$dashboardWidget->setPosition($this->dashboardWidgetManager->calculateNextPosition($dashboardWidget->getDashboard()));
$this->dashboardWidgetManager->checkAccess($dashboardWidget, 'write');
$settings = $dashboardWidget->getSettings();
if (isset($settings['missionInstructions'])){
$dataSource = $dashboardWidget->getDatasource();
$mission = $this->missionManager->getMissionByIdOrUuid($dataSource['missions'][0]);
$settings['missionInstructions'] = html_entity_decode(strip_tags($mission->getInstructions()));
$dashboardWidget->setSettings($settings);
}
}
public function apiPreUpdate(ViewEvent $event)
{
$dashboardWidget = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$this->isDashboardWidget($dashboardWidget) || $method !== Request::METHOD_PUT) {
return;
}
$this->preUpdate($dashboardWidget);
}
public function preUpdate(DashboardWidget $dashboardWidget)
{
$this->dashboardWidgetManager->checkAccess($dashboardWidget, 'write');
}
public function apiPreDelete(ViewEvent $event)
{
$dashboardWidget = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$this->isDashboardWidget($dashboardWidget) || $method !== Request::METHOD_DELETE) {
return;
}
$this->preUpdate($dashboardWidget);
}
private function isDashboardWidget($dashboardWidget): bool
{
return $dashboardWidget instanceof DashboardWidget;
}
}