Files
myep/src/Validator/Constraints/PurchaseVoucherValidator.php
T

49 lines
1.5 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Validator\Constraints;
use App\Form\Model\ParticipantEditDto;
use App\Service\VoucherValidationService;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class PurchaseVoucherValidator extends ConstraintValidator
{
public function __construct(
private readonly VoucherValidationService $voucherValidationService,
) {
}
public function validate(mixed $value, Constraint $constraint): void
{
if (!$constraint instanceof PurchaseVoucher) {
throw new UnexpectedTypeException($constraint, PurchaseVoucher::class);
}
if (!$value instanceof ParticipantEditDto) {
throw new UnexpectedTypeException($value, ParticipantEditDto::class);
}
$voucherCode = $value->participant->purchaseVoucherCode;
// Skip validation if voucher code is empty
if (null === $voucherCode || '' === trim($voucherCode)) {
return;
}
// Validate voucher via API
$result = $this->voucherValidationService->validatePurchaseVoucher($voucherCode);
// Add violation if voucher is invalid
if (false === $result->isValid) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ error }}', $result->errorMessage ?? 'Unbekannter Fehler')
->atPath('participant.purchaseVoucherCode')
->addViolation();
}
}
}