Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DDLS-426 : Prevent user from inputting invalid year during registration #1781

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
5 changes: 4 additions & 1 deletion client/app/src/Entity/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@
use App\Entity\Report\Report;
use App\Entity\Traits\ActiveAudit;
use App\Entity\Traits\IsSoftDeleteableEntity;
use DateTime;
use App\Validator\Constraints as AppAssert;
use Doctrine\Common\Collections\ArrayCollection;
use JMS\Serializer\Annotation as JMS;
use Symfony\Component\Validator\Constraints as Assert;

/**
* @AppAssert\YearMustBeFourDigitsAndValid(groups={"client-court-date"})
*/
class Client
{
use IsSoftDeleteableEntity;
Expand Down
2 changes: 2 additions & 0 deletions client/app/src/Entity/Report/Report.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
*
* @AppAssert\EndDateNotBeforeStartDate(groups={"start-end-dates"})
*
* @AppAssert\YearMustBeFourDigitsAndValid(groups={"start-end-dates"})
*
* @AppAssert\ProfDeputyCostsEstimate\CostBreakdownNotGreaterThanTotal(groups={"prof-deputy-estimate-costs"})
*
* @Assert\Callback(callback="debtsValid", groups={"debts"})
Expand Down
6 changes: 3 additions & 3 deletions client/app/src/Form/ClientType.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ public function buildForm(FormBuilderInterface $builder, array $options)
->add('address5', FormTypes\TextType::class)
->add('postcode', FormTypes\TextType::class)
->add('country', FormTypes\CountryType::class, [
'preferred_choices' => ['GB'],
'placeholder' => 'country.defaultOption',
'preferred_choices' => ['GB'],
'placeholder' => 'country.defaultOption',
])
->add('phone', FormTypes\TextType::class)
->add('id', FormTypes\HiddenType::class)
Expand All @@ -50,7 +50,7 @@ public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'translation_domain' => 'registration',
'validation_groups' => 'lay-deputy-client',
'validation_groups' => ['lay-deputy-client', 'client-court-date'],
]);
}

Expand Down
34 changes: 21 additions & 13 deletions client/app/src/Form/Report/ReportType.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,33 @@
use Symfony\Component\Form\Extension\Core\Type as FormTypes;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Range;

class ReportType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('id', FormTypes\HiddenType::class)
->add('startDate', FormTypes\DateType::class, ['widget' => 'text',
'input' => 'datetime',
'format' => 'yyyy-MM-dd',
'invalid_message' => 'report.startDate.invalidMessage', ])

->add('endDate', FormTypes\DateType::class, ['widget' => 'text',
'input' => 'datetime',
'format' => 'yyyy-MM-dd',
'invalid_message' => 'report.endDate.invalidMessage',
])

->add('save', FormTypes\SubmitType::class);
->add('id', FormTypes\HiddenType::class)
->add('startDate', FormTypes\DateType::class, ['widget' => 'text',
'input' => 'datetime',
'format' => 'yyyy-MM-dd',
'invalid_message' => 'report.startDate.invalidMessage',
'constraints' => [
new Range([
'min' => (new \DateTime('now'))->modify('-7 years'),
'max' => (new \DateTime('now'))->modify('+3 years'),
'notInRangeMessage' => 'Please enter a valid start date.',
'groups' => 'start-end-dates',
]),
],
])
->add('endDate', FormTypes\DateType::class, ['widget' => 'text',
'input' => 'datetime',
'format' => 'yyyy-MM-dd',
'invalid_message' => 'report.endDate.invalidMessage',
])
->add('save', FormTypes\SubmitType::class);
}

public function configureOptions(OptionsResolver $resolver)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace App\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
* @Annotation
*/
class YearMustBeFourDigitsAndValid extends Constraint
{
public string $message = 'Please enter a valid four-digit year.';

public function validatedBy()
{
return static::class.'Validator';
}

/**
* @return array|string
*/
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

namespace App\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class YearMustBeFourDigitsAndValidValidator extends ConstraintValidator
{
public function validate($data, Constraint $constraint)
{
$startAndEndDate = [];
$courtDate = new \DateTime();

if ($data instanceof StartEndDateComparableInterface) {
$startAndEndDate = [$data->getStartDate(), $data->getEndDate()];

foreach ($startAndEndDate as $date) {
if (!$date instanceof \DateTime) {
return;
}
}
} else {
$courtDate = $data->getCourtDate();

if (!$courtDate instanceof \DateTime) {
return;
}
}

if ($startAndEndDate) {
$count = count(array_filter($startAndEndDate, function ($date) {
$year = $date->format('Y');

// if the year does not start with a 2 and is not 4 digits long add to count
return !preg_match('/^2\d{3}$/', $year);
}));

if ($count > 0) {
$this->context
->buildViolation($constraint->message)
->addViolation();
}
} else {
$year = $courtDate->format('Y');

if (!preg_match('/^2\d{3}$/', $year)) {
$this->context
->buildViolation($constraint->message)
->addViolation();
}
}
}
}
85 changes: 85 additions & 0 deletions client/app/tests/phpunit/Form/ReportTypeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php

namespace App\Form;

use App\Form\Report\ReportType;
use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
use Symfony\Component\Form\Test\TypeTestCase;
use Symfony\Component\Validator\Validation;

class ReportTypeTest extends TypeTestCase
{
// ensures validation constraints are applied
protected function getExtensions(): array
{
$validator = Validation::createValidator();

return [
new ValidatorExtension($validator),
];
}

public function testSubmitValidYear()
{
$currentDate = new \DateTime();
$currentYear = $currentDate->format('Y');
$followingYear = $currentDate->modify('+1 year')->format('Y');

$startDate = [
'year' => $currentYear,
'month' => '01',
'day' => '02',
];

$endDate = [
'year' => $followingYear,
'month' => '01',
'day' => '02',
];

$formData = [
'id' => 1,
'startDate' => $startDate,
'endDate' => $endDate,
];

$form = $this->factory->create(ReportType::class);

$form->submit($formData);

$this->assertTrue($form->isSubmitted());
$this->assertTrue($form->isValid());
}

public function testSubmitInvalidYear()
{
$startDate = [
'year' => '2000',
'month' => '01',
'day' => '02',
];

$endDate = [
'year' => '2001',
'month' => '01',
'day' => '02',
];

$formData = [
'id' => 1,
'startDate' => $startDate,
'endDate' => $endDate,
];

$form = $this->factory->create(ReportType::class);

$form->submit($formData);
$errors = $form['startDate']->getErrors();

$this->assertTrue($form->isSubmitted());
$this->assertFalse($form->isValid());

$this->assertCount(1, $errors);
$this->assertSame('Please enter a valid year.', $errors[0]->getMessage());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?php

namespace App\Validator\Constraints;

use App\TestHelpers\ClientHelpers;
use App\TestHelpers\ReportHelpers;
use PHPUnit\Framework\TestCase;

class YearMustBeFourDigitsAndValidValidatorTest extends TestCase
{
/**
* @return YearMustBeFourDigitsAndValidValidator
*/
public function configureValidator(?string $expectedMessage = null)
{
// mock the violation builder
$builder = $this->getMockBuilder('Symfony\Component\Validator\Violation\ConstraintViolationBuilder')
->disableOriginalConstructor()
->setMethods(['addViolation'])
->getMock();

// mock the validator context
$context = $this->getMockBuilder('Symfony\Component\Validator\Context\ExecutionContext')
->disableOriginalConstructor()
->setMethods(['buildViolation'])
->getMock();

if ($expectedMessage) {
$builder->expects($this->once())
->method('addViolation');

$context->expects($this->once())
->method('buildViolation')
->with($this->equalTo($expectedMessage))
->will($this->returnValue($builder));
} else {
$context->expects($this->never())
->method('buildViolation');
}

// initialize the validator with the mocked context
$validator = new YearMustBeFourDigitsAndValidValidator();
$validator->initialize($context);

return $validator;
}

/**
* Verify a constraint message is triggered when court date year is invalid.
*/
public function testValidateOnInvalidCourtDate()
{
$constraint = new YearMustBeFourDigitsAndValid();
$validator = $this->configureValidator($constraint->message);

$client = ClientHelpers::createClient();
$client->setCourtDate(new \DateTime('0116-01-01'));

$validator->validate($client, $constraint);
}

/**
* Verify no constraint message is triggered when court date year is valid.
*/
public function testValidateOnValidCourtDate()
{
$constraint = new YearMustBeFourDigitsAndValid();
$validator = $this->configureValidator();

$client = ClientHelpers::createClient();
$client->setCourtDate(new \DateTime('today'));

$validator->validate($client, $constraint);
}

/**
* Verify a constraint message is triggered when reporting period year is invalid.
*/
public function testValidateOnInvalidYear()
{
$constraint = new YearMustBeFourDigitsAndValid();
$validator = $this->configureValidator($constraint->message);

$client = ReportHelpers::createReport();
$client->setStartDate(new \DateTime('0116-01-02'));
$client->setEndDate(new \DateTime('0117-01-01'));

$validator->validate($client, $constraint);
}

/**
* Verify no constraint message is triggered when reporting period year is valid.
*/
public function testValidateOnValidYear()
{
$constraint = new YearMustBeFourDigitsAndValid();
$validator = $this->configureValidator();

$client = ReportHelpers::createReport();
$client->setStartDate(new \DateTime('today'));
$client->setEndDate((new \DateTime('today'))->modify('+1 year'));

$validator->validate($client, $constraint);
}
}
1 change: 1 addition & 0 deletions client/app/translations/validators.en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ report:
invalidMessage: "Enter a valid date in this format: DD/MM/YYYY"
beforeStart: "Check the end date: it cannot be before the start date"
greaterThan15Months: "Check the end date: your reporting period cannot be more than 15 months"
invalidYear: Please enter a valid year
dueDate:
notBlank: Enter the new due date
invalidMessage: "Enter a valid date in this format: DD/MM/YYYY"
Expand Down
Loading