<?php
declare(strict_types=1);
namespace App\Form\EventListener\Poll;
use App\Entity\Poll\Poll;
use App\Entity\Poll\Question;
use App\Entity\Poll\ResponseAnswerText;
use App\Entity\Poll\ResponseAnswerSingle;
use App\Entity\Poll\ResponseAnswerMulti;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
/**
* @author Przemysław Chrupek <przemyslaw.chrupek@avt.pl>
* @package App\Form\EventListener
*/
class ResponseQuestionsFormListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [FormEvents::PRE_SET_DATA => 'preSetData'];
}
public function preSetData(FormEvent $event)
{
$response = $event->getData();
$poll = $response->getPoll();
if (!$poll instanceof Poll)
return;
$form = $event->getForm();
if ($poll->getWithEmail()) {
$emailParams = [];
if ($poll->getEmailRequired()) {
$emailParams = [
'required' => true,
'constraints' => [
new NotBlank([
'message' => 'Wpisz email'
]),
new Length([
'max' => 250,
'maxMessage' => 'Maksymalnie 250 znaków',
]),
new Email([
'message' => 'Adres email jest nieprawidłowy'
]),
],
];
}
$form->add(
'email',
EmailType::class,
$emailParams
);
}
foreach ($poll->getQuestions() as $question) {
if ($response->getResponseAnswers()->contains($question))
continue;
switch ($question->getType()) {
case Question::TYPE_SELECT:
case Question::TYPE_RADIO:
$responseAnswer = new ResponseAnswerSingle;
break;
case Question::TYPE_MULTISELECT:
case Question::TYPE_CHECKBOX:
$responseAnswer = new ResponseAnswerMulti;
break;
default:
$responseAnswer = new ResponseAnswerText;
break;
}
$responseAnswer->setQuestion($question);
$response->addResponseAnswer($responseAnswer);
}
$event->setData($response);
}
}