Refactor PersonControllerUpdateTest: separate validation test on dedicated test

This commit is contained in:
2023-08-29 14:30:03 +02:00
parent 80684f65fe
commit 52d791f6d0
5 changed files with 139 additions and 191 deletions

View File

@@ -28,4 +28,6 @@ class Birthdate extends Constraint
final public const BIRTHDATE_INVALID_CODE = '3f42fd96-0b2d-11ec-8cf3-0f3b1b1ca1c4';
public $message = 'The birthdate must be before %date%';
public $belowMessage = 'The birthdate must be after %date%';
}

View File

@@ -14,17 +14,27 @@ namespace Chill\PersonBundle\Validator\Constraints\Person;
use DateInterval;
use DateTime;
use LogicException;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use function get_class;
use function gettype;
use function is_object;
class BirthdateValidator extends ConstraintValidator
{
public function __construct(private $interval_spec = null)
{
private string $interval_spec;
private string $below_interval = 'P150Y';
public function __construct(
private ParameterBagInterface $parameterBag,
private ClockInterface $clock
) {
$this->interval_spec = $this->parameterBag->get('chill_person')['validation']['birthdate_not_after'];
}
public function validate($value, Constraint $constraint)
@@ -38,27 +48,40 @@ class BirthdateValidator extends ConstraintValidator
. (get_debug_type($value)));
}
if (!$constraint instanceof Birthdate) {
throw new UnexpectedTypeException($constraint, Birthdate::class);
}
$limitDate = $this->getLimitDate();
if ($limitDate < $value) {
if ($value > $limitDate) {
$this->context->buildViolation($constraint->message)
->setParameter('%date%', $limitDate->format('d-m-Y'))
->setCode(Birthdate::BIRTHDATE_INVALID_CODE)
->addViolation();
}
if ($value < $this->getBelowLimitDate()) {
$this->context->buildViolation($constraint->belowMessage)
->setParameter('%date%', $this->getBelowLimitDate()->format('d-m-Y'))
->setCode(Birthdate::BIRTHDATE_INVALID_CODE)
->addViolation();
}
}
/**
* @return DateTime
*/
private function getLimitDate()
private function getLimitDate(): DateTime
{
if (null !== $this->interval_spec) {
$interval = new DateInterval($this->interval_spec);
return (new DateTime('now'))->sub($interval);
return DateTime::createFromImmutable($this->clock->now()->sub($interval));
}
return new DateTime('now');
return DateTime::createFromImmutable($this->clock->now());
}
private function getBelowLimitDate(): DateTime
{
return DateTime::createFromImmutable($this->clock->now()->sub(new DateInterval($this->below_interval)));
}
}