| 123456789101112131415161718192021222324252627282930313233343536373839404142 |
- <?php
- declare(strict_types=1);
- namespace App\Validator\Constraints;
- use Symfony\Component\Validator\Constraint;
- use Symfony\Component\Validator\ConstraintValidator;
- use Symfony\Component\Validator\Exception\UnexpectedTypeException;
- class LessThanFieldValidator extends ConstraintValidator
- {
- public function validate(mixed $object, Constraint $constraint): void
- {
- if (!$constraint instanceof LessThanField) {
- throw new UnexpectedTypeException($constraint, LessThanField::class);
- }
- if (!is_object($object)) {
- return; // Only validate objects
- }
- $fieldValue = $object->{$constraint->field} ?? null;
- $comparedValue = $object->{$constraint->comparedTo} ?? null;
- if ($fieldValue === null || $comparedValue === null) {
- return; // Skip if either value is null
- }
- if (!$fieldValue instanceof \DateTimeInterface || !$comparedValue instanceof \DateTimeInterface) {
- return;
- }
- if ($fieldValue->getTimestamp() >= $comparedValue->getTimestamp()) {
- $this->context
- ->buildViolation($constraint->message)
- ->setParameter('{{ field }}', $constraint->field)
- ->setParameter('{{ comparedTo }}', $constraint->comparedTo)
- ->atPath($constraint->field)
- ->addViolation();
- }
- }
- }
|