LessThanFieldValidator.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Validator\Constraints;
  4. use Symfony\Component\Validator\Constraint;
  5. use Symfony\Component\Validator\ConstraintValidator;
  6. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  7. class LessThanFieldValidator extends ConstraintValidator
  8. {
  9. public function validate(mixed $object, Constraint $constraint): void
  10. {
  11. if (!$constraint instanceof LessThanField) {
  12. throw new UnexpectedTypeException($constraint, LessThanField::class);
  13. }
  14. if (!is_object($object)) {
  15. return; // Only validate objects
  16. }
  17. $fieldValue = $object->{$constraint->field} ?? null;
  18. $comparedValue = $object->{$constraint->comparedTo} ?? null;
  19. if ($fieldValue === null || $comparedValue === null) {
  20. return; // Skip if either value is null
  21. }
  22. if (!$fieldValue instanceof \DateTimeInterface || !$comparedValue instanceof \DateTimeInterface) {
  23. return;
  24. }
  25. if ($fieldValue->getTimestamp() >= $comparedValue->getTimestamp()) {
  26. $this->context
  27. ->buildViolation($constraint->message)
  28. ->setParameter('{{ field }}', $constraint->field)
  29. ->setParameter('{{ comparedTo }}', $constraint->comparedTo)
  30. ->atPath($constraint->field)
  31. ->addViolation();
  32. }
  33. }
  34. }