Правило CardScheme
Правило CardScheme вешается на поле формы
или свойство сущности и проверяет, что номер карты
принадлежит указанной платёжной системе. В параметре
schemes передаётся массив или строка с названиями
схем: VISA, MASTERCARD, AMEX, MIR,
CHINA_UNIONPAY, DINERS, DISCOVER,
INSTAPAYMENT, JCB, LASER, MAESTRO,
UNIONPAY, UATP. Если номер карты не
соответствует ни одной из схем, форма считается
невалидной.
Синтаксис
#[Assert\CardScheme(schemes: ['VISA', 'MASTERCARD'])]
Пример
Давайте создадим сущность Payment с полем
cardNumber и повесим на него правило CardScheme:
<?php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Payment
{
#[Assert\CardScheme(schemes: ['VISA', 'MASTERCARD'])]
private string $cardNumber;
public function setCardNumber(string $cardNumber): void
{
$this->cardNumber = $cardNumber;
}
public function getCardNumber(): string
{
return $this->cardNumber;
}
}
?>
Пример
Давайте проверим валидацию номера карты через
ValidatorInterface:
<?php
namespace App\Controller;
use App\Entity\Payment;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class PaymentController extends AbstractController
{
#[Route('/payment', name: 'payment_check')]
public function check(ValidatorInterface $validator): Response
{
$payment = new Payment();
$payment->setCardNumber('4111111111111111');
$errors = $validator->validate($payment);
if (count($errors) > 0) {
return new Response((string) $errors);
}
return new Response('card is valid');
}
}
?>
Результат выполнения кода:
"card is valid"
Пример
Давайте передадим заведомо неподходящий номер карты
для схемы VISA и посмотрим на ошибку:
<?php
namespace App\Controller;
use App\Entity\Payment;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class PaymentController extends AbstractController
{
#[Route('/payment-invalid', name: 'payment_invalid')]
public function invalid(ValidatorInterface $validator): Response
{
$payment = new Payment();
$payment->setCardNumber('5555555555554444');
$errors = $validator->validate($payment);
if (count($errors) > 0) {
return new Response($errors[0]->getMessage());
}
return new Response('card is valid');
}
}
?>
Результат выполнения кода:
"Card scheme "MASTERCARD" is not allowed. Allowed schemes: "VISA""
Пример
Давайте используем правило CardScheme прямо
в форме FormType вместе с типом TextType:
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;
class PaymentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('cardNumber', TextType::class, [
'constraints' => [
new Assert\CardScheme([
'schemes' => ['VISA', 'MASTERCARD', 'MIR'],
]),
],
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => null,
]);
}
}
?>