<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\FenceOfferElement;
use App\Entity\SectionLayout;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class FenceOfferElementSubscriber implements EventSubscriberInterface
{
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['addSectionLayouts', EventPriorities::PRE_SERIALIZE],
];
}
public function addSectionLayouts(ViewEvent $event)
{
$fenceOfferElement = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if ($fenceOfferElement instanceof FenceOfferElement && $method === Request::METHOD_GET) {
$sectionLayouts = $this->entityManager->getRepository(SectionLayout::class)->findByType($fenceOfferElement->getFenceElement()->getType() ?? '', $fenceOfferElement->getFenceElement()->getElementType() ?? '');
$formConfigJson = $fenceOfferElement->getFenceElement()->getFormConfigJson();
$formConfigJson['section_layouts'] = $this->prepareSectionLayouts($sectionLayouts);
$fenceOfferElement->getFenceElement()->setFormConfigJson($formConfigJson);
}
}
private function prepareSectionLayouts(array $sectionLayouts): array
{
$elements = [];
foreach ($sectionLayouts as $sectionLayout) {
$elements[] = [
'id' => $sectionLayout->getId(),
'name' => $sectionLayout->getName(),
'data' => $sectionLayout->getLayout(),
'type' => $sectionLayout->getType(),
];
}
return $elements;
}
}