<?php
declare(strict_types=1);
namespace App\Form\EventListener\Admin\Webhook;
use App\Entity\Admin\Webhook\WebhookInterface;
use App\Form\FormHelper;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class AddEventsFieldSubscriber extends FormHelper implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [FormEvents::PRE_SET_DATA => 'preSetData'];
}
public function preSetData(FormEvent $event): void
{
$choices = [];
$webhook = $event->getData();
$events = null !== $webhook->getId() ? $this->getEventStates($webhook->getObject()) : array_merge(WebhookInterface::ORDER_EVENTS, WebhookInterface::SYNC_EVENTS);
foreach ($events as $state) {
$choices['app.admin.pages.webhook.states.' . $state] = $state;
}
$event->getForm()->add('events', ChoiceType::class, $this->getChoiceParameters(
'app.admin.pages.webhook.list.events',
self::PLACEHOLDER_NONE,
true,
[
'choices' => $choices,
'data' => \count($webhook->getEvents()) > 0 ? $webhook->getEvents() : [],
'multiple' => true,
'expanded' => false,
'choice_attr' => static fn ($choice, $key, $value) => true === \in_array($choice, WebhookInterface::ORDER_EVENTS, true) ? ['data-event-type' => 'order'] : ['data-event-type' => 'sync'],
]
));
}
private function getEventStates(string $object): array
{
return WebhookInterface::OBJECT_ORDER === $object ? WebhookInterface::ORDER_EVENTS : WebhookInterface::SYNC_EVENTS;
}
}