wip: email uniqueness validation

This commit is contained in:
Björn Fromme
2026-03-16 11:59:11 +01:00
parent 54a3145710
commit 89979d6ce4
11 changed files with 549 additions and 783 deletions
+37 -24
View File
@@ -5,6 +5,7 @@ namespace App\Form;
use App\BusProNet\Form\CountryType;
use App\Form\Model\BookingDto;
use App\Form\Model\ParticipantDto;
use App\Form\Model\ParticipantEditDto;
use App\Form\Service\Contract\FieldOptionsProviderInterface;
use App\Form\Service\Contract\FieldStateProviderInterface;
use App\Form\Service\CreateFieldStateProvider;
@@ -72,10 +73,10 @@ class BookingParticipantType extends AbstractType
return;
}
/** @var ParticipantDto $participant */
$participant = $form->getData();
/** @var ParticipantEditDto $data */
$data = $form->getData();
if (null === $participant || false === property_exists($participant, 'index')) {
if (null === $data || null === $data->participant) {
return;
}
@@ -83,7 +84,7 @@ class BookingParticipantType extends AbstractType
$this->fieldHandlerRegistry->processFieldsForParticipant(
$submittedData,
$bookingContext,
$participant->index
$data->participant->index
);
}
@@ -92,28 +93,27 @@ class BookingParticipantType extends AbstractType
*/
private function onPreSetData(FormEvent $event, ?BookingDto $bookingContext): void
{
/** @var ParticipantDto|null $participantData */
$participantData = $event->getData();
/** @var ParticipantEditDto|null $data */
$data = $event->getData();
if (null === $participantData) {
if (null === $data) {
return;
}
$form = $event->getForm();
// Card flow: BookingDto passed via options
// Accordion flow (if we had one): traverse form tree
$bookingDto = $bookingContext ?? $this->fieldStateProvider->getBookingDtoFromForm($form);
// Use bookingContext from wrapper DTO or fallback to passed option
$bookingDto = $data->bookingContext ?? $bookingContext ?? $this->fieldStateProvider->getBookingDtoFromForm($form);
if (null === $bookingDto) {
return;
}
// Add base fields with states applied
$this->addBaseFields($form, $bookingDto, $participantData->index);
$this->addBaseFields($form, $bookingDto, $data->participant->index);
// Add dynamic fields
$this->addDynamicFields($form, $bookingDto, $participantData->index);
$this->addDynamicFields($form, $bookingDto, $data->participant->index);
}
/**
@@ -124,22 +124,22 @@ class BookingParticipantType extends AbstractType
$submittedData = $event->getData();
$form = $event->getForm();
// Card flow: BookingDto passed via options
// Accordion flow (if we had one): traverse form tree
$bookingDto = $bookingContext ?? $this->fieldStateProvider->getBookingDtoFromForm($form);
/** @var ParticipantEditDto $data */
$data = $form->getData();
if (null === $data || null === $data->participant) {
return;
}
// Use bookingContext from wrapper DTO or fallback to passed option
$bookingDto = $data->bookingContext ?? $bookingContext ?? $this->fieldStateProvider->getBookingDtoFromForm($form);
if (null === $bookingDto) {
return;
}
// Get participant index from form data
$participantData = $form->getData();
if (null === $participantData || false === property_exists($participantData, 'index')) {
return;
}
// Rebuild all fields with updated states based on submitted data
$this->rebuildFieldsWithStates($form, $bookingDto, $participantData->index, $submittedData);
$this->rebuildFieldsWithStates($form, $bookingDto, $data->participant->index, $submittedData);
$event->setData($submittedData);
}
@@ -159,16 +159,19 @@ class BookingParticipantType extends AbstractType
->add('firstName', TextType::class, $this->mergeFieldState([
'label' => 'Vorname',
'sanitize_html' => true,
'property_path' => 'participant.firstName',
], $getFieldState('firstName')))
->add('lastName', TextType::class, $this->mergeFieldState([
'label' => 'Nachname',
'sanitize_html' => true,
'property_path' => 'participant.lastName',
], $getFieldState('lastName')))
->add('dateOfBirth', BirthdayType::class, $this->mergeFieldState([
'label' => 'Geburtsdatum',
'widget' => 'text',
'input' => 'datetime_immutable',
'html5' => false,
'property_path' => 'participant.dateOfBirth',
], $getFieldState('dateOfBirth')))
->add('gender', ChoiceType::class, $this->mergeFieldState([
'label' => 'Geschlecht',
@@ -179,28 +182,35 @@ class BookingParticipantType extends AbstractType
'weiblich' => 'W',
'divers' => 'D',
],
'property_path' => 'participant.gender',
], $getFieldState('gender')))
->add('nationality', CountryType::class, $this->mergeFieldState([
'label' => 'Nationalität',
'property' => 'nationality',
'preferred_choices' => ['D', 'A', 'CH'],
'property_path' => 'participant.nationality',
], $getFieldState('nationality')))
->add('email', EmailType::class, $this->mergeFieldState([
'label' => 'E-Mail',
'property_path' => 'participant.email',
], $getFieldState('email')))
->add('mobile', TextType::class, $this->mergeFieldState([
'label' => 'Telefon (mobil)',
'required' => false,
'sanitize_html' => true,
'property_path' => 'participant.mobile',
], $getFieldState('mobile')))
->add('address', AddressType::class, $this->mergeFieldState([
'label' => 'Adresse',
'required' => false,
'property_path' => 'participant.address',
], $getFieldState('address')));
// Add body dimensions with state handling - use shouldIncludeField method
if ($this->fieldStateProvider->shouldIncludeField('bodyDimensions', $bookingDto, $participantIndex)) {
$form->add('bodyDimensions', BodyDimensionsType::class);
$form->add('bodyDimensions', BodyDimensionsType::class, [
'property_path' => 'participant',
]);
}
}
@@ -300,6 +310,9 @@ class BookingParticipantType extends AbstractType
continue;
}
// Add property_path for wrapper DTO navigation
$fieldOptions['property_path'] = 'participant.'.$fieldName;
// Apply non-hidden field states (readonly, disabled, required)
if (true === $this->fieldStateProvider->hasStateConditions($fieldName)) {
$fieldState = $this->fieldStateProvider->getFieldState($fieldName, $bookingDto, $participantIndex);
@@ -371,7 +384,7 @@ class BookingParticipantType extends AbstractType
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => ParticipantDto::class,
'data_class' => ParticipantEditDto::class,
'selected_rooms' => [],
'booking_context' => null,
]);
-39
View File
@@ -196,43 +196,4 @@ class BookingDto
}
}
#[Assert\Callback(groups: ['booking_create', 'booking_edit'])]
public function validateEmailUniqueness(ExecutionContextInterface $context): void
{
// Build map of email addresses to participant indices (adults only)
$emailMap = [];
foreach ($this->participants as $index => $participant) {
// Skip children (they can share email addresses)
if (true === $participant->isChild()) {
continue;
}
// Skip null or empty emails (handled by other validators)
if (null === $participant->email || '' === trim($participant->email)) {
continue;
}
// Normalize email for case-insensitive comparison
$normalizedEmail = strtolower(trim($participant->email));
// Add participant index to the email map
if (false === isset($emailMap[$normalizedEmail])) {
$emailMap[$normalizedEmail] = [];
}
$emailMap[$normalizedEmail][] = $index;
}
// Add validation errors for duplicate emails
foreach ($emailMap as $email => $indices) {
// Only add violations if email is used by multiple adult participants
if (1 < count($indices)) {
foreach ($indices as $index) {
$context->buildViolation('Diese E-Mail Adresse wird bereits von einem anderen erwachsenen Teilnehmer verwendet')
->atPath(sprintf('participants[%d].email', $index))
->addViolation();
}
}
}
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace App\Form\Model;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Wrapper DTO for editing a participant within a booking context.
*
* This wrapper enables clean validation of participant email uniqueness
* without requiring back-references or form coupling. It contains both
* the participant being edited and the full booking context needed for
* cross-participant validation.
*/
class ParticipantEditDto
{
public function __construct(
#[Assert\Valid]
public readonly ParticipantDto $participant,
public readonly BookingDto $bookingContext,
) {
}
/**
* Validates that adult participants have unique email addresses.
*
* Children (under 16) are exempt from this validation and can share
* email addresses with adults. Email comparison is case-insensitive
* and whitespace is normalized.
*/
#[Assert\Callback(groups: ['booking_create', 'booking_edit'])]
public function validateEmailUniqueness(ExecutionContextInterface $context): void
{
// Skip validation for children (under 16)
if (true === $this->participant->isChild()) {
return;
}
// Skip if email is null or empty (handled by @Email and @NotBlank constraints)
if (null === $this->participant->email || '' === trim($this->participant->email)) {
return;
}
// Normalize current participant's email for comparison
$normalizedEmail = strtolower(trim($this->participant->email));
// Check against all adult participants in booking context
foreach ($this->bookingContext->participants as $index => $otherParticipant) {
// Skip self-comparison (same participant index)
if ($index === $this->participant->index) {
continue;
}
// Skip children (they can share email addresses)
if (true === $otherParticipant->isChild()) {
continue;
}
// Skip null or empty emails
if (null === $otherParticipant->email || '' === trim($otherParticipant->email)) {
continue;
}
// Compare normalized emails
$otherNormalizedEmail = strtolower(trim($otherParticipant->email));
if ($normalizedEmail === $otherNormalizedEmail) {
// Add violation to participant.email path
$context->buildViolation('Diese E-Mail Adresse wird bereits von einem anderen Teilnehmer verwendet')
->atPath('participant.email')
->addViolation();
// Stop after first duplicate found (no need to report multiple times)
return;
}
}
}
}
@@ -1,138 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Form\Service;
use App\Form\Model\BookingDto;
use App\Form\Service\Abstract\AbstractParticipantFieldHandler;
/**
* Handles email uniqueness validation for booking participants.
*
* This handler provides real-time feedback during form refresh when an adult
* participant enters an email address that is already used by another adult
* participant in the same booking. Children (under 16) are exempt from this
* validation and can share email addresses with adults or other children.
*
* The handler adds warning notifications during the HTMX refresh cycle,
* providing immediate user feedback without blocking form submission.
* Hard validation is enforced via BookingDto::validateEmailUniqueness()
* when the user attempts to proceed to the next step.
*/
class ParticipantEmailFieldHandler extends AbstractParticipantFieldHandler
{
/**
* Returns the form field name this handler processes.
*
* @return string The field name 'email'
*/
public function getFieldName(): string
{
return 'email';
}
/**
* Returns the field dependencies for proper processing order.
*
* Email validation has no dependencies on other fields.
*
* @return string[] Empty array (no dependencies)
*/
public function getDependencies(): array
{
return [];
}
/**
* Determines if this handler should process the field based on submitted data.
*
* Email validation should always run when the email field is present in
* the submitted data, regardless of booking mode or participant index.
*
* @param array<string, mixed> $submittedData The submitted participant form data
* @param string $mode The booking mode (BookingDto::MODE_CREATE or MODE_EDIT)
* @param int $participantIndex The index of the participant being processed
*
* @return bool True if email field exists in submitted data
*/
public function shouldProcess(array $submittedData, string $mode, int $participantIndex): bool
{
return array_key_exists($this->getFieldName(), $submittedData);
}
/**
* Processes the email field for a specific participant.
*
* This method checks if the participant's email address is already used by
* another adult participant in the same booking. If a duplicate is found,
* a warning notification is added to the participant for display as a toast.
*
* Validation rules:
* - Children (under 16 at current date) are exempt from uniqueness validation
* - Null or empty emails are skipped (handled by Symfony's @Assert\Email)
* - Only duplicates with other adult participants trigger warnings
*
* @param array<string, mixed> $submittedData The submitted participant form data
* @param BookingDto $bookingDto The booking DTO to update (create or edit)
* @param int $participantIndex The index of the participant being processed
*/
public function processField(array $submittedData, BookingDto $bookingDto, int $participantIndex): void
{
// Safely get the participant object, returning early if not found
$participant = $this->getParticipant($bookingDto, $participantIndex);
if (null === $participant) {
return;
}
// Skip validation for children (they can share email addresses)
if (true === $participant->isChild()) {
return;
}
// Get the email value from submitted data (field handlers run in PRE_SUBMIT, before form binding)
$email = $submittedData[$this->getFieldName()] ?? null;
// Skip if email is null or empty (handled by other validators)
if (null === $email || '' === trim($email)) {
return;
}
// Normalize email for comparison (case-insensitive)
$normalizedEmail = strtolower(trim($email));
// Check for duplicate emails among other adult participants
$hasDuplicate = false;
foreach ($bookingDto->participants as $index => $otherParticipant) {
// Skip comparing with self
if ($index === $participantIndex) {
continue;
}
// Skip if other participant is a child (children can share emails)
if (true === $otherParticipant->isChild()) {
continue;
}
// Skip if other participant has no email
if (null === $otherParticipant->email || '' === trim($otherParticipant->email)) {
continue;
}
// Compare normalized emails
$otherNormalizedEmail = strtolower(trim($otherParticipant->email));
if ($normalizedEmail === $otherNormalizedEmail) {
$hasDuplicate = true;
break;
}
}
// Add warning notification if duplicate found
if (true === $hasDuplicate) {
$participant->addNotification(
'warning',
'Diese E-Mail Adresse wird bereits von einem anderen erwachsenen Teilnehmer verwendet'
);
}
}
}