<?php
declare(strict_types=1);
namespace Harmonizely\Form\EventListener;
use Harmonizely\Model\EventTypeInterface;
use Harmonizely\Model\EventTypeUser;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
class AddLocationLabelFieldSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
FormEvents::PRE_SUBMIT => 'preSubmit',
];
}
public function preSubmit(FormEvent $event): void
{
$data = $event->getData();
if (empty($data) || !array_key_exists('locationType', $data)) {
return;
}
if (EventTypeInterface::LOCATION_TYPE_REQUEST === $data['locationType']) {
$form = $event->getForm();
$isFirst = $this->isFirstWithRequestLocationType($form);
$constraints = [new Length(['max' => 255])];
if ($isFirst) {
$constraints[] = new NotBlank();
}
$form->add('locationLabel', TextType::class, [
'constraints' => $constraints,
]);
}
}
private function isFirstWithRequestLocationType(FormInterface $form): bool
{
$parent = $form->getParent();
if ($parent === null) {
return true;
}
foreach ($parent->all() as $siblingForm) {
if ($siblingForm === $form) {
return true;
}
$siblingData = $siblingForm->getData();
if ($siblingData instanceof EventTypeUser
&& $siblingData->getLocationType() === EventTypeInterface::LOCATION_TYPE_REQUEST) {
return false;
}
}
return true;
}
}