fix: don't require email address from participants under 16

This commit is contained in:
2026-09-01 15:15:58 +02:00
parent 98e0cfcf6f
commit f595183c05
11 changed files with 566 additions and 36 deletions
+1 -1
View File
@@ -209,7 +209,7 @@ class BookingParticipantType extends AbstractType
if ($this->fieldStateProvider->shouldIncludeField('email', $bookingDto, $participantIndex)) { if ($this->fieldStateProvider->shouldIncludeField('email', $bookingDto, $participantIndex)) {
$form->add('email', EmailType::class, $this->mergeFieldState([ $form->add('email', EmailType::class, $this->mergeFieldState([
'label' => 'E-Mail', 'label' => 'E-Mail',
'required' => !$personalDataOptional, 'required' => false,
'property_path' => 'participant.email', 'property_path' => 'participant.email',
'attr' => [ 'attr' => [
'autocomplete' => 'leave-me-alone-chrome', 'autocomplete' => 'leave-me-alone-chrome',
+33 -4
View File
@@ -12,11 +12,20 @@ use App\BusProNet\Model\Service;
use App\Validator\Constraints as AppAssert; use App\Validator\Constraints as AppAssert;
use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface; use Symfony\Component\Validator\Context\ExecutionContextInterface;
use function Symfony\Component\String\u; use function Symfony\Component\String\u;
#[AppAssert\Participant(groups: ['booking_edit', 'booking_create'])] #[AppAssert\Participant(groups: ['booking_edit', 'booking_create'])]
class ParticipantDto class ParticipantDto
{ {
/**
* Age below which a participant counts as a child.
*
* Children may share an email address with an adult and are not required to have one of
* their own; both rules go through isChild(), so this is the only place the age lives.
*/
public const CHILD_AGE_THRESHOLD = 16;
/** /**
* List of dynamic participant fields that can be conditionally hidden/shown. * List of dynamic participant fields that can be conditionally hidden/shown.
*/ */
@@ -70,8 +79,14 @@ class ParticipantDto
#[Assert\NotNull(message: 'Bitte angeben', groups: ['strict_required'])] #[Assert\NotNull(message: 'Bitte angeben', groups: ['strict_required'])]
public ?\DateTimeImmutable $dateOfBirth = null; public ?\DateTimeImmutable $dateOfBirth = null;
// Requiredness is delegated to requiresOwnEmail() so the constraint and the field state
// conditions cannot state the rule differently.
#[Assert\Email(message: 'Bitte eine gültige E-Mail Adresse angeben', mode: 'strict', groups: ['booking_edit', 'booking_create'])] #[Assert\Email(message: 'Bitte eine gültige E-Mail Adresse angeben', mode: 'strict', groups: ['booking_edit', 'booking_create'])]
#[Assert\NotBlank(message: 'Bitte angeben', groups: ['strict_required'])] #[Assert\When(
expression: 'this.requiresOwnEmail()',
constraints: [new Assert\NotBlank(message: 'Bitte angeben')],
groups: ['strict_required']
)]
public ?string $email = null; public ?string $email = null;
public ?string $mobile = null; public ?string $mobile = null;
@@ -345,11 +360,25 @@ class ParticipantDto
* A child is defined as someone under the specified age threshold (default: 16 years). * A child is defined as someone under the specified age threshold (default: 16 years).
* This classification is used for email uniqueness validation (children can share emails with adults). * This classification is used for email uniqueness validation (children can share emails with adults).
* *
* @param int $ageThreshold The age threshold for child classification (default: 16)
*
* @return bool True if participant is under the age threshold, false otherwise or if age unknown * @return bool True if participant is under the age threshold, false otherwise or if age unknown
*/ */
public function isChild(int $ageThreshold = 16): bool /**
* Decides whether this participant has to supply an email address of their own.
*
* The applicant is the booking's contact and always has to be reachable. Everyone else only
* needs an address once they are old enough to have one, so children are exempt. An unknown
* date of birth counts as an adult, following isChild().
*
* Single source for the rule: the Assert\When on $email enforces it, and the 'required'
* field state conditions in CreateFieldStateProvider/EditFieldStateProvider render the
* matching mandatory marker.
*/
public function requiresOwnEmail(): bool
{
return $this->isApplicant() || false === $this->isChild();
}
public function isChild(int $ageThreshold = self::CHILD_AGE_THRESHOLD): bool
{ {
$age = $this->getAge(); $age = $this->getAge();
@@ -113,7 +113,9 @@ abstract class AbstractFieldStateProvider implements FieldStateProviderInterface
* Supported state types: * Supported state types:
* - 'readonly': Adds readonly HTML attribute to the field * - 'readonly': Adds readonly HTML attribute to the field
* - 'disabled': Disables the field completely * - 'disabled': Disables the field completely
* - 'required': Makes the field mandatory * - 'required': Determines whether the field is mandatory. Unlike the states above this is
* authoritative in both directions: the condition result is assigned as-is, so it can also
* clear a 'required' option set by the form type.
* - 'static_text': Field should be rendered as static text (checked separately via shouldRenderAsStaticText()) * - 'static_text': Field should be rendered as static text (checked separately via shouldRenderAsStaticText())
* - 'hidden': Field excluded from form entirely (checked via shouldIncludeField()) * - 'hidden': Field excluded from form entirely (checked via shouldIncludeField())
* *
@@ -137,20 +139,30 @@ abstract class AbstractFieldStateProvider implements FieldStateProviderInterface
$attributes = []; $attributes = [];
foreach ($this->fieldStateConditions[$fieldName] as $stateType => $condition) { foreach ($this->fieldStateConditions[$fieldName] as $stateType => $condition) {
if ($condition->evaluate($bookingDto, $participantIndex, $formData)) { $isMet = $condition->evaluate($bookingDto, $participantIndex, $formData);
switch ($stateType) {
case 'readonly': // 'required' is a determination the provider owns outright, so it is assigned either
$attributes['readonly'] = true; // way and can clear the form type's base option. 'readonly' and 'disabled' are
break; // escalations: a condition can only ever switch them on, never hand back control of a
case 'disabled': // field the form type deliberately locked down.
$stateModifications['disabled'] = true; if ('required' === $stateType) {
break; $stateModifications['required'] = $isMet;
case 'required': continue;
$stateModifications['required'] = true; }
break;
// Note: 'static_text' and 'hidden' are intentionally not handled here if (false === $isMet) {
// They are checked via shouldRenderAsStaticText() and shouldIncludeField() continue;
} }
switch ($stateType) {
case 'readonly':
$attributes['readonly'] = true;
break;
case 'disabled':
$stateModifications['disabled'] = true;
break;
// Note: 'static_text' and 'hidden' are intentionally not handled here
// They are checked via shouldRenderAsStaticText() and shouldIncludeField()
} }
} }
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace App\Form\Service\Condition;
use App\Form\Model\BookingDto;
use App\Form\Service\Contract\FieldConditionInterface;
/**
* Condition that checks whether the booking belongs to an internal agency.
*
* Internal agency bookings are made by staff on behalf of a customer, so they are exempt
* from several rules that protect customer-entered data: personal data stays editable and
* fields that are mandatory for customers may be left blank.
*
* This is the plain flag on its own. FirstParticipantReadOnlyCondition and
* PersonalDataMutabilityCondition also consult it, but combine it with further criteria.
*/
class InternalAgencyBookingCondition implements FieldConditionInterface
{
/**
* Evaluates whether the booking is an internal agency booking.
*
* @param BookingDto $bookingDto The current booking data (create or edit)
* @param int $participantIndex The index of the participant being evaluated (unused)
* @param array<string, mixed> $formData Current form data (unused)
*
* @return bool True if the booking was made by an internal agency
*/
public function evaluate(BookingDto $bookingDto, int $participantIndex, array $formData): bool
{
return $bookingDto->isInternalAgencyBooking();
}
/**
* The agency code is a property of the booking, not of any form field.
*
* @return string[] Always empty
*/
public function getDependentFields(): array
{
return [];
}
public function getDescription(): string
{
return 'Checks if the booking is an internal agency booking';
}
}
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace App\Form\Service\Condition;
use App\Form\Model\BookingDto;
use App\Form\Service\Contract\FieldConditionInterface;
/**
* Condition that mirrors ParticipantDto::requiresOwnEmail() into the field state layer.
*
* It deliberately holds no logic of its own. The rule for who needs an email address is
* enforced by the Assert\When on ParticipantDto::$email; this condition exists so the
* mandatory marker rendered next to the field is derived from that same method rather than
* from a second, independently maintained composition of age and applicant conditions.
*/
class RequiresOwnEmailCondition implements FieldConditionInterface
{
/**
* Evaluates whether the participant has to supply an email address of their own.
*
* @param BookingDto $bookingDto The current booking data (create or edit)
* @param int $participantIndex The index of the participant being evaluated
* @param array<string, mixed> $formData Current form data (unused)
*
* @return bool True if the participant needs their own email address
*/
public function evaluate(BookingDto $bookingDto, int $participantIndex, array $formData): bool
{
$participant = $bookingDto->getParticipant($participantIndex);
// A participant that does not exist yet is treated as needing an address, matching the
// "unknown counts as an adult" stance of ParticipantDto::isChild().
return null === $participant || $participant->requiresOwnEmail();
}
/**
* The rule reads the date of birth, so the state has to be recalculated when it changes.
*
* @return string[] Array containing 'dateOfBirth'
*/
public function getDependentFields(): array
{
return ['dateOfBirth'];
}
public function getDescription(): string
{
return 'Checks if the participant needs an email address of their own';
}
}
@@ -20,6 +20,7 @@ use App\Form\Service\Condition\FirstParticipantReadOnlyCondition;
use App\Form\Service\Condition\MultipleParticipantsCondition; use App\Form\Service\Condition\MultipleParticipantsCondition;
use App\Form\Service\Condition\RentalInsuranceAvailableCondition; use App\Form\Service\Condition\RentalInsuranceAvailableCondition;
use App\Form\Service\Condition\RentalSelectionCondition; use App\Form\Service\Condition\RentalSelectionCondition;
use App\Form\Service\Condition\RequiresOwnEmailCondition;
use App\Form\Service\Condition\RoomSelectionCondition; use App\Form\Service\Condition\RoomSelectionCondition;
use App\Form\Service\Condition\ServiceSubTypeCondition; use App\Form\Service\Condition\ServiceSubTypeCondition;
use App\Form\Service\Condition\SingleRoomTypeCondition; use App\Form\Service\Condition\SingleRoomTypeCondition;
@@ -113,6 +114,7 @@ class CreateFieldStateProvider extends AbstractFieldStateProvider
$this->fieldStateConditions['email'] = [ $this->fieldStateConditions['email'] = [
'static_text' => $firstParticipantReadOnlyCondition, 'static_text' => $firstParticipantReadOnlyCondition,
'required' => new RequiresOwnEmailCondition(),
]; ];
// Mobile field: static text for first participant (when read-only), required for first participant (guest bookings) // Mobile field: static text for first participant (when read-only), required for first participant (guest bookings)
+17 -16
View File
@@ -7,7 +7,6 @@ namespace App\Form\Service;
use App\BusProNet\Utility\DirectionMapper; use App\BusProNet\Utility\DirectionMapper;
use App\Form\Model\BookingDto; use App\Form\Model\BookingDto;
use App\Form\Service\Abstract\AbstractFieldStateProvider; use App\Form\Service\Abstract\AbstractFieldStateProvider;
use App\Form\Service\Contract\FieldConditionInterface;
use App\Form\Service\Condition\AdditionalServicesMutabilityCondition; use App\Form\Service\Condition\AdditionalServicesMutabilityCondition;
use App\Form\Service\Condition\AgeRangeCondition; use App\Form\Service\Condition\AgeRangeCondition;
use App\Form\Service\Condition\BookingModeCondition; use App\Form\Service\Condition\BookingModeCondition;
@@ -16,10 +15,12 @@ use App\Form\Service\Condition\DateOfBirthProvidedCondition;
use App\Form\Service\Condition\FieldValueCondition; use App\Form\Service\Condition\FieldValueCondition;
use App\Form\Service\Condition\FirstParticipantCondition; use App\Form\Service\Condition\FirstParticipantCondition;
use App\Form\Service\Condition\FirstParticipantReadOnlyCondition; use App\Form\Service\Condition\FirstParticipantReadOnlyCondition;
use App\Form\Service\Condition\InternalAgencyBookingCondition;
use App\Form\Service\Condition\PersonalDataMutabilityCondition; use App\Form\Service\Condition\PersonalDataMutabilityCondition;
use App\Form\Service\Condition\PickupsMutabilityCondition; use App\Form\Service\Condition\PickupsMutabilityCondition;
use App\Form\Service\Condition\RentalInsuranceAvailableCondition; use App\Form\Service\Condition\RentalInsuranceAvailableCondition;
use App\Form\Service\Condition\RentalSelectionCondition; use App\Form\Service\Condition\RentalSelectionCondition;
use App\Form\Service\Condition\RequiresOwnEmailCondition;
use App\Form\Service\Condition\RoomSelectionCondition; use App\Form\Service\Condition\RoomSelectionCondition;
use App\Form\Service\Condition\ServiceSubTypeCondition; use App\Form\Service\Condition\ServiceSubTypeCondition;
use App\Form\Service\Condition\SkiPassSelectionCondition; use App\Form\Service\Condition\SkiPassSelectionCondition;
@@ -69,16 +70,8 @@ class EditFieldStateProvider extends AbstractFieldStateProvider
// TODO: Remove the block below and move 'firstName', 'lastName', 'dateOfBirth' into the // TODO: Remove the block below and move 'firstName', 'lastName', 'dateOfBirth' into the
// 'gender'/'nationality' loop once BPN reliably handles name and date-of-birth changes for participants. // 'gender'/'nationality' loop once BPN reliably handles name and date-of-birth changes for participants.
// Until then, name and DOB are always read-only for non-internal agency regardless of the BPN flag. // Until then, name and DOB are always read-only for non-internal agency regardless of the BPN flag.
$corePersonalDataReadOnlyCondition = new class implements FieldConditionInterface { $internalAgencyBookingCondition = new InternalAgencyBookingCondition();
public function evaluate(BookingDto $bookingDto, int $participantIndex, array $formData): bool $corePersonalDataReadOnlyCondition = CompositeCondition::not($internalAgencyBookingCondition);
{
return !$bookingDto->isInternalAgencyBooking();
}
public function getDependentFields(): array { return []; }
public function getDescription(): string { return 'Name and DOB always read-only for non-internal agency (temporary)'; }
};
foreach (['firstName', 'lastName', 'dateOfBirth'] as $field) { foreach (['firstName', 'lastName', 'dateOfBirth'] as $field) {
$this->fieldStateConditions[$field] = ['static_text' => $corePersonalDataReadOnlyCondition]; $this->fieldStateConditions[$field] = ['static_text' => $corePersonalDataReadOnlyCondition];
} }
@@ -92,11 +85,19 @@ class EditFieldStateProvider extends AbstractFieldStateProvider
} }
// Contact fields: only the applicant (index 0) is read-only — participants can always update email/phone // Contact fields: only the applicant (index 0) is read-only — participants can always update email/phone
foreach (['email', 'mobile'] as $field) { $this->fieldStateConditions['mobile'] = [
$this->fieldStateConditions[$field] = [ 'static_text' => $firstParticipantReadOnlyCondition,
'static_text' => $firstParticipantReadOnlyCondition, ];
];
} // Same rule as the create flow, except that internal agency bookings leave personal
// data optional throughout.
$this->fieldStateConditions['email'] = [
'static_text' => $firstParticipantReadOnlyCondition,
'required' => CompositeCondition::and(
CompositeCondition::not($internalAgencyBookingCondition),
new RequiresOwnEmailCondition(),
),
];
// Address fields - render as static text if first participant in non-internal agency OR participant not mutable // Address fields - render as static text if first participant in non-internal agency OR participant not mutable
$this->fieldStateConditions['address'] = [ $this->fieldStateConditions['address'] = [
+56
View File
@@ -204,4 +204,60 @@ class ParticipantDtoTest extends TestCase
return $insurance; return $insurance;
} }
public function testRequiresOwnEmailIsFalseForNonApplicantChild(): void
{
$participant = new ParticipantDto();
$participant->index = 1;
$participant->dateOfBirth = new \DateTimeImmutable('2015-01-01');
$this->assertFalse($participant->requiresOwnEmail());
}
public function testRequiresOwnEmailIsTrueForNonApplicantAdult(): void
{
$participant = new ParticipantDto();
$participant->index = 1;
$participant->dateOfBirth = new \DateTimeImmutable('1990-01-01');
$this->assertTrue($participant->requiresOwnEmail());
}
public function testRequiresOwnEmailIsTrueForTheApplicantEvenAsAChild(): void
{
$participant = new ParticipantDto();
$participant->index = 0;
$participant->dateOfBirth = new \DateTimeImmutable('2015-01-01');
$this->assertTrue(
$participant->requiresOwnEmail(),
'The applicant is the booking contact and always has to be reachable'
);
}
public function testRequiresOwnEmailTreatsUnknownAgeAsAdult(): void
{
$participant = new ParticipantDto();
$participant->index = 1;
$participant->dateOfBirth = null;
$this->assertTrue($participant->requiresOwnEmail());
}
public function testRequiresOwnEmailBoundaryAtChildAgeThreshold(): void
{
$exactlyThreshold = new ParticipantDto();
$exactlyThreshold->index = 1;
$exactlyThreshold->dateOfBirth = (new \DateTimeImmutable('today'))
->modify(sprintf('-%d years', ParticipantDto::CHILD_AGE_THRESHOLD));
$oneDayShort = new ParticipantDto();
$oneDayShort->index = 1;
$oneDayShort->dateOfBirth = (new \DateTimeImmutable('today'))
->modify(sprintf('-%d years', ParticipantDto::CHILD_AGE_THRESHOLD))
->modify('+1 day');
$this->assertTrue($exactlyThreshold->requiresOwnEmail());
$this->assertFalse($oneDayShort->requiresOwnEmail());
}
} }
+156
View File
@@ -30,6 +30,7 @@ use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\EmailValidator; use Symfony\Component\Validator\Constraints\EmailValidator;
use Symfony\Component\Validator\ConstraintValidatorFactoryInterface; use Symfony\Component\Validator\ConstraintValidatorFactoryInterface;
use Symfony\Component\Validator\ConstraintValidatorInterface; use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\Validator\Validation; use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Validator\ValidatorInterface; use Symfony\Component\Validator\Validator\ValidatorInterface;
@@ -856,6 +857,161 @@ class ParticipantEditDtoTest extends TestCase
* available ski pass. Ski pass validation depends on the travel actually offering * available ski pass. Ski pass validation depends on the travel actually offering
* passes, so a travel without them is a distinct fixture, not the default. * passes, so a travel without them is a distinct fixture, not the default.
*/ */
public function testChildWithoutEmailPassesStrictValidation(): void
{
$bookingDto = $this->createBookingDtoWithParticipants([
$this->createAdultParticipant('[email protected]'),
$this->createChildParticipant(''),
]);
$violations = $this->validateStrict($bookingDto, 1);
$this->assertSame([], $this->emailRequiredMessages($violations));
}
public function testChildWithNullEmailPassesStrictValidation(): void
{
$child = $this->createChildParticipant('');
$child->email = null;
$bookingDto = $this->createBookingDtoWithParticipants([
$this->createAdultParticipant('[email protected]'),
$child,
]);
$violations = $this->validateStrict($bookingDto, 1);
$this->assertSame([], $this->emailRequiredMessages($violations));
}
public function testChildWithMalformedEmailStillFailsEmailFormatValidation(): void
{
$bookingDto = $this->createBookingDtoWithParticipants([
$this->createAdultParticipant('[email protected]'),
$this->createChildParticipant('not-an-email'),
]);
$violations = $this->validator->validate(
new ParticipantEditDto(
participant: $bookingDto->participants[1],
bookingContext: $bookingDto,
),
null,
['booking_create', 'strict_required']
);
$messages = [];
foreach ($violations as $violation) {
if ('participant.email' === $violation->getPropertyPath()) {
$messages[] = $violation->getMessage();
}
}
$this->assertSame(['Bitte eine gültige E-Mail Adresse angeben'], $messages);
}
public function testAdultDependentWithoutEmailFailsStrictValidation(): void
{
$bookingDto = $this->createBookingDtoWithParticipants([
$this->createAdultParticipant('[email protected]'),
$this->createAdultParticipant(''),
]);
$violations = $this->validateStrict($bookingDto, 1);
$this->assertSame(['Bitte angeben'], $this->emailRequiredMessages($violations));
}
public function testDependentWithUnknownDateOfBirthAndNoEmailFailsStrictValidation(): void
{
$participant = $this->createAdultParticipant('');
$participant->dateOfBirth = null;
$bookingDto = $this->createBookingDtoWithParticipants([
$this->createAdultParticipant('[email protected]'),
$participant,
]);
$violations = $this->validateStrict($bookingDto, 1);
$this->assertSame(['Bitte angeben'], $this->emailRequiredMessages($violations));
}
public function testApplicantChildWithoutEmailStillFailsStrictValidation(): void
{
$bookingDto = $this->createBookingDtoWithParticipants([
$this->createChildParticipant(''),
$this->createAdultParticipant('[email protected]'),
]);
$violations = $this->validateStrict($bookingDto, 0);
$this->assertSame(['Bitte angeben'], $this->emailRequiredMessages($violations));
}
public function testDependentTurningExactlySixteenRequiresEmail(): void
{
$participant = $this->createAdultParticipant('');
$participant->dateOfBirth = (new \DateTimeImmutable('today'))->modify('-16 years');
$bookingDto = $this->createBookingDtoWithParticipants([
$this->createAdultParticipant('[email protected]'),
$participant,
]);
$violations = $this->validateStrict($bookingDto, 1);
$this->assertSame(['Bitte angeben'], $this->emailRequiredMessages($violations));
}
public function testDependentOneDayShortOfSixteenDoesNotRequireEmail(): void
{
$participant = $this->createAdultParticipant('');
$participant->dateOfBirth = (new \DateTimeImmutable('today'))->modify('-16 years')->modify('+1 day');
$bookingDto = $this->createBookingDtoWithParticipants([
$this->createAdultParticipant('[email protected]'),
$participant,
]);
$violations = $this->validateStrict($bookingDto, 1);
$this->assertSame([], $this->emailRequiredMessages($violations));
}
/**
* Validates one participant with the strict group active, as the booking create flow does.
*/
private function validateStrict(BookingDto $bookingDto, int $index): ConstraintViolationListInterface
{
return $this->validator->validate(
new ParticipantEditDto(
participant: $bookingDto->participants[$index],
bookingContext: $bookingDto,
),
null,
['booking_create', 'strict_required']
);
}
/**
* Narrows a violation list down to the "email is mandatory" messages.
*
* @return list<string>
*/
private function emailRequiredMessages(ConstraintViolationListInterface $violations): array
{
$messages = [];
foreach ($violations as $violation) {
if ('participant.email' === $violation->getPropertyPath() && 'Bitte angeben' === $violation->getMessage()) {
$messages[] = $violation->getMessage();
}
}
return $messages;
}
private function createTravelOfferingSkiPasses(?int $ageFrom = null): Travel private function createTravelOfferingSkiPasses(?int $ageFrom = null): Travel
{ {
$travel = $this->createTravelWithoutSkiPasses(); $travel = $this->createTravelWithoutSkiPasses();
@@ -73,4 +73,95 @@ class CreateFieldStateProviderTest extends TestCase
'Dependent insurance field must reappear once the applicant switches away from family insurance' 'Dependent insurance field must reappear once the applicant switches away from family insurance'
); );
} }
public function testEmailIsNotRequiredForNonApplicantChild(): void
{
$bookingDto = $this->createBookingDtoWithApplicantAndDependent(new \DateTimeImmutable('2015-01-01'));
$this->assertFalse(
$this->provider->getFieldState('email', $bookingDto, 1)['required'],
'A child travelling with an applicant does not need an email address of their own'
);
}
public function testEmailIsRequiredForNonApplicantAdult(): void
{
$bookingDto = $this->createBookingDtoWithApplicantAndDependent(new \DateTimeImmutable('1990-01-01'));
$this->assertTrue($this->provider->getFieldState('email', $bookingDto, 1)['required']);
}
public function testEmailIsRequiredForTheApplicantEvenAsAChild(): void
{
$bookingDto = $this->createBookingDtoWithApplicantAndDependent(new \DateTimeImmutable('2015-01-01'));
$bookingDto->participants[0]->dateOfBirth = new \DateTimeImmutable('2015-01-01');
$this->assertTrue(
$this->provider->getFieldState('email', $bookingDto, 0)['required'],
'The applicant is the booking contact and always has to be reachable'
);
}
public function testEmailIsRequiredWhenDateOfBirthIsUnknown(): void
{
$bookingDto = $this->createBookingDtoWithApplicantAndDependent(new \DateTimeImmutable('2015-01-01'));
$bookingDto->participants[1]->dateOfBirth = null;
$this->assertTrue(
$this->provider->getFieldState('email', $bookingDto, 1)['required'],
'An unknown age counts as an adult'
);
}
public function testEmailRequirementFlipsWhenDateOfBirthChanges(): void
{
$bookingDto = $this->createBookingDtoWithApplicantAndDependent(new \DateTimeImmutable('2015-01-01'));
$dependent = $bookingDto->participants[1];
$this->assertFalse($this->provider->getFieldState('email', $bookingDto, 1)['required']);
$dependent->dateOfBirth = new \DateTimeImmutable('1990-01-01');
$this->assertTrue(
$this->provider->getFieldState('email', $bookingDto, 1)['required'],
'Correcting a child date of birth to an adult one must reinstate the requirement'
);
}
/**
* Guards the switch from add-only to toggling 'required' state: the two fields that already
* used a 'required' condition must keep behaving exactly as before, now reporting false
* instead of omitting the key. Both declare 'required' => false as their base in the form
* type, so assigning the condition result either way is equivalent to the old add-only pass.
*/
public function testMobileAndAddressRemainRequiredOnlyForTheFirstParticipant(): void
{
$bookingDto = $this->createBookingDtoWithApplicantAndDependent(new \DateTimeImmutable('1990-01-01'));
$this->assertTrue($this->provider->getFieldState('mobile', $bookingDto, 0)['required']);
$this->assertFalse($this->provider->getFieldState('mobile', $bookingDto, 1)['required']);
$this->assertTrue($this->provider->getFieldState('address', $bookingDto, 0)['required']);
$this->assertFalse($this->provider->getFieldState('address', $bookingDto, 1)['required']);
}
private function createBookingDtoWithApplicantAndDependent(\DateTimeImmutable $dependentDateOfBirth): BookingDto
{
$travel = new Travel();
$travel->dateFrom = new \DateTimeImmutable('+30 days');
$travel->dateTo = new \DateTimeImmutable('+37 days');
$applicant = new ParticipantDto();
$applicant->index = 0;
$applicant->dateOfBirth = new \DateTimeImmutable('1980-01-01');
$dependent = new ParticipantDto();
$dependent->index = 1;
$dependent->dateOfBirth = $dependentDateOfBirth;
$bookingDto = new BookingDto($travel, 1);
$bookingDto->participants = [$applicant, $dependent];
return $bookingDto;
}
} }
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace App\Tests\Form\Service;
use App\BusProNet\Model\Travel;
use App\BusProNet\XmlLoader\AgencyLoader;
use App\Form\Model\BookingDto;
use App\Form\Model\ParticipantDto;
use App\Form\Service\EditFieldStateProvider;
use PHPUnit\Framework\TestCase;
/**
* Covers the edit-flow email requirement, which follows the same age rule as the create flow
* but stands down entirely for internal agency bookings, where staff leave personal data blank.
*/
class EditFieldStateProviderTest extends TestCase
{
private EditFieldStateProvider $provider;
protected function setUp(): void
{
$this->provider = new EditFieldStateProvider();
}
public function testEmailIsRequiredForNonApplicantAdult(): void
{
$bookingDto = $this->createBookingDto(new \DateTimeImmutable('1990-01-01'), false);
$this->assertTrue($this->provider->getFieldState('email', $bookingDto, 1)['required']);
}
public function testEmailIsNotRequiredForNonApplicantChild(): void
{
$bookingDto = $this->createBookingDto(new \DateTimeImmutable('2015-01-01'), false);
$this->assertFalse($this->provider->getFieldState('email', $bookingDto, 1)['required']);
}
public function testEmailIsNotRequiredForInternalAgencyBookingsEvenForAdults(): void
{
$bookingDto = $this->createBookingDto(new \DateTimeImmutable('1990-01-01'), true);
$this->assertFalse(
$this->provider->getFieldState('email', $bookingDto, 1)['required'],
'Internal agency bookings leave personal data optional throughout'
);
}
public function testEmailIsRequiredForTheApplicantOutsideInternalAgencyBookings(): void
{
$bookingDto = $this->createBookingDto(new \DateTimeImmutable('1990-01-01'), false);
$this->assertTrue($this->provider->getFieldState('email', $bookingDto, 0)['required']);
}
private function createBookingDto(\DateTimeImmutable $dependentDateOfBirth, bool $internalAgency): BookingDto
{
$travel = new Travel();
$travel->dateFrom = new \DateTimeImmutable('+30 days');
$travel->dateTo = new \DateTimeImmutable('+37 days');
$applicant = new ParticipantDto();
$applicant->index = 0;
$applicant->dateOfBirth = new \DateTimeImmutable('1980-01-01');
$dependent = new ParticipantDto();
$dependent->index = 1;
$dependent->dateOfBirth = $dependentDateOfBirth;
$bookingDto = new BookingDto($travel, 1);
$bookingDto->participants = [$applicant, $dependent];
if (true === $internalAgency) {
$bookingDto->agencyCode = AgencyLoader::INTERNAL_AGENCY_CODE;
}
return $bookingDto;
}
}