Skip to content

Commit

Permalink
Make validation great again 🚀
Browse files Browse the repository at this point in the history
  • Loading branch information
arti0090 committed Oct 19, 2024
1 parent f2ef368 commit 218e2b7
Show file tree
Hide file tree
Showing 13 changed files with 137 additions and 59 deletions.
3 changes: 3 additions & 0 deletions assets/shop/checkout_complete_entrypoint.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,8 @@ import './js/_visa_mobile';
import {CardForm} from "./js/card_form";

document.addEventListener('DOMContentLoaded', () => {
if (!document.querySelector('[name="sylius_checkout_complete"]').querySelector('[data-tpay-card-holder-name]')) {
return;
}
new CardForm('[name="sylius_checkout_complete"]');
});
23 changes: 17 additions & 6 deletions assets/shop/js/_visa_mobile.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
document.addEventListener('DOMContentLoaded', () => {
const COUNTRY_CODED_MOBILE_PHONE_LENGTH = 11;
const MOBILE_PHONE_MIN_LENGTH = 7;
const MOBILE_PHONE_MAX_LENGTH = 15;

let form = document.querySelector('[name="sylius_checkout_complete"]');
let phoneNumber = form.querySelector('[data-visa-mobile-phone-number]');
let phoneNumber = form.querySelector('#sylius_checkout_complete_tpay_visa_mobile_phone_number');

if (null === phoneNumber) {
return;
Expand All @@ -29,16 +30,26 @@ document.addEventListener('DOMContentLoaded', () => {
function validateVisaMobilePhoneNumber(field) {
let fieldLength = field.value.length;

if (fieldLength === COUNTRY_CODED_MOBILE_PHONE_LENGTH) {
if (MOBILE_PHONE_MIN_LENGTH <= fieldLength && fieldLength <= MOBILE_PHONE_MAX_LENGTH) {
clearErrors(phoneNumber);
return;
}

if (fieldLength === 0) {
addError(phoneNumber, 'validationErrorRequired');
addError(phoneNumber);
return;
}

if (fieldLength < MOBILE_PHONE_MIN_LENGTH) {
addError(phoneNumber, 'validationErrorMinLength');
return;
}

if (fieldLength > MOBILE_PHONE_MAX_LENGTH) {
addError(phoneNumber, 'validationErrorMaxLength');
return;
}

addError(phoneNumber);
}

Expand All @@ -49,14 +60,14 @@ document.addEventListener('DOMContentLoaded', () => {
errorContainer.innerHTML = '';
}

function addError(field, validationErrorName = 'validationErrorLength') {
function addError(field, validationErrorName = 'validationErrorRequired') {
const tpayField = field.closest('[data-tpay-field]');
const errorContainer = tpayField.querySelector('[data-tpay-error-container]');

errorContainer.innerHTML = createErrorElement(field, validationErrorName);
}

function createErrorElement(field, validationErrorName = 'validationErrorLength') {
function createErrorElement(field, validationErrorName = 'validationErrorRequired') {
const errorMessage = field.dataset[validationErrorName];

return `
Expand Down
2 changes: 0 additions & 2 deletions config/services/form.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,6 @@

$services->set('commerce_weavers_sylius_tpay.form.data_transformer.card_type', CardTypeDataTransformer::class);

$services->set('commerce_weavers_sylius_tpay.form.data_transformer.visa_mobile_phone', VisaMobilePhoneDataTransformer::class);

$services
->set('commerce_weavers_sylius_tpay.form.event_listener.decrypt_gateway_config', DecryptGatewayConfigListener::class)
->args([
Expand Down
33 changes: 0 additions & 33 deletions src/Form/DataTransformer/VisaMobilePhoneDataTransformer.php

This file was deleted.

7 changes: 2 additions & 5 deletions src/Form/Type/TpayPaymentDetailsType.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace CommerceWeavers\SyliusTpayPlugin\Form\Type;

use CommerceWeavers\SyliusTpayPlugin\Form\DataTransformer\VisaMobilePhoneDataTransformer;
use CommerceWeavers\SyliusTpayPlugin\Validator\Constraint\EncodedGooglePayToken;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
Expand Down Expand Up @@ -74,11 +73,11 @@ public function buildForm(FormBuilderInterface $builder, array $options): void
'property_path' => '[visa_mobile_phone_number]',
'attr' => [
'placeholder' => 'commerce_weavers_sylius_tpay.shop.order_summary.visa_mobile.placeholder',
'maxLength' => 9,
'maxLength' => 15,
],
'validation_groups' => ['sylius_checkout_complete'],
'constraints' => [
new Length(min: 9, groups: ['sylius_checkout_complete']),
new Length(min: 7, max: 15, groups: ['sylius_checkout_complete']),
new Regex(
'/^\d+$/',
message: 'commerce_weavers_sylius_tpay.shop.pay.visa_mobile.regex',
Expand All @@ -88,8 +87,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void
],
);

$builder->get('visa_mobile_phone_number')->addModelTransformer(new VisaMobilePhoneDataTransformer());

$builder->addEventListener(
FormEvents::PRE_SUBMIT,
[$this->removeUnnecessaryPaymentDetailsFieldsListener, '__invoke'],
Expand Down
1 change: 1 addition & 0 deletions src/Model/PaymentDetails.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public function __construct(
private ?string $successUrl = null,
private ?string $failureUrl = null,
private ?string $tpayChannelId = null,
#[\SensitiveParameter]
private ?string $visaMobilePhoneNumber = null,
) {
}
Expand Down
5 changes: 3 additions & 2 deletions templates/shop/cart/complete/_visaMobile.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@
<div class="field required" data-tpay-field>
{{ form_label(form.tpay.visa_mobile_phone_number) }}
<div class="ui left labeled input">
<div class="ui label">+48</div>
<div class="ui label">+</div>
{{ form_widget(form.tpay.visa_mobile_phone_number, {
attr: {
'data-locale': app.request.locale|slice(3, 2),
'data-validation-error-length': 'commerce_weavers_sylius_tpay.shop.pay.visa_mobile.length'|trans({}, 'validators'),
'data-validation-error-min-length': 'commerce_weavers_sylius_tpay.shop.pay.visa_mobile.min_length'|trans({}, 'validators'),
'data-validation-error-max-length': 'commerce_weavers_sylius_tpay.shop.pay.visa_mobile.max_length'|trans({}, 'validators'),
'data-validation-error-required': 'commerce_weavers_sylius_tpay.shop.pay.visa_mobile.required'|trans({}, 'validators'),
}
}) }}
Expand Down
9 changes: 0 additions & 9 deletions tests/E2E/Checkout/TpayPaymentCheckoutTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,4 @@ public function test_it_completes_the_checkout_using_blik(): void

$this->assertPageTitleContains('Waiting for payment');
}

public function test_it_completes_the_checkout_using_visa_mobile(): void
{
$this->processWithPaymentMethod('tpay_visa_mobile');
$this->fillVisaMobile(self::FORM_ID, '123123123');
$this->placeOrder();

$this->assertPageTitleContains('Waiting for payment');
}
}
98 changes: 98 additions & 0 deletions tests/E2E/Checkout/TpayVisaMobileCheckoutTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?php

declare(strict_types=1);

namespace Tests\CommerceWeavers\SyliusTpayPlugin\E2E\Checkout;

use Tests\CommerceWeavers\SyliusTpayPlugin\E2E\E2ETestCase;
use Tests\CommerceWeavers\SyliusTpayPlugin\E2E\Helper\Account\LoginShopUserTrait;
use Tests\CommerceWeavers\SyliusTpayPlugin\E2E\Helper\Order\CartTrait;
use Tests\CommerceWeavers\SyliusTpayPlugin\E2E\Helper\Order\TpayTrait;

final class TpayVisaMobileCheckoutTest extends E2ETestCase
{
use CartTrait;
use TpayTrait;
use LoginShopUserTrait;

private const FORM_ID = 'sylius_checkout_complete';

protected function setUp(): void
{
parent::setUp();

$this->loadFixtures(['addressed_cart.yaml']);

$this->loginShopUser('[email protected]', 'sylius');
$this->showSelectingShippingMethodStep();
$this->processWithDefaultShippingMethod();
}

public function test_it_throws_validation_error_if_phone_number_is_too_short(): void
{
$this->processWithPaymentMethod('tpay_visa_mobile');
$this->fillVisaMobile(self::FORM_ID, '123123');
$this->placeOrder();

$validationElement = $this->findElementByXpath("//div[contains(@class, 'sylius-validation-error')]");
$this->assertNotNull($validationElement);
$this->assertSame(
"The mobile phone must be composed minimum of 7 digits.",
$validationElement->getText()
);
}

public function test_it_trims_input_phone_number_if_it_is_too_long(): void
{
$inputValueMaxLength = 15;

$this->processWithPaymentMethod('tpay_visa_mobile');
$this->fillVisaMobile(self::FORM_ID, '1234567890123456789');

$inputValue = $this
->findElementByXpath("//input[@id='sylius_checkout_complete_tpay_visa_mobile_phone_number']")
->getAttribute('value')
;

$expectedValue = '123456789012345';
$this->assertSame('123456789012345', $inputValue);
$this->assertSame($inputValueMaxLength, strlen($expectedValue));
}

public function test_it_throws_validation_error_if_phone_number_contains_non_digit_character(): void
{
$this->processWithPaymentMethod('tpay_visa_mobile');
$this->fillVisaMobile(self::FORM_ID, '+12312312');
$this->placeOrder();

$validationElement = $this->findElementByXpath("//div[contains(@class, 'sylius-validation-error')]");
$this->assertNotNull($validationElement);
$this->assertSame(
"The mobile phone must consist only of digits.",
$validationElement->getText()
);
}

public function test_it_throws_validation_error_if_phone_number_is_empty(): void
{
$this->processWithPaymentMethod('tpay_visa_mobile');
$this->fillVisaMobile(self::FORM_ID, '');
$this->placeOrder();

$validationElement = $this->findElementByXpath("//div[contains(@class, 'sylius-validation-error')]");
$this->assertNotNull($validationElement);
$this->assertSame(
"The mobile phone number is required.",
$validationElement->getText()
);
}

public function test_it_completes_the_checkout_using_visa_mobile(): void
{
$this->processWithPaymentMethod('tpay_visa_mobile');
$this->fillVisaMobile(self::FORM_ID, '123123123');
$this->placeOrder();

$this->assertPageTitleContains('Waiting for payment');
}
}
6 changes: 6 additions & 0 deletions tests/E2E/Helper/Order/TpayTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Tests\CommerceWeavers\SyliusTpayPlugin\E2E\Helper\Order;

use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverElement;
use Symfony\Component\Panther\Client;

/**
Expand All @@ -30,4 +31,9 @@ public function fillVisaMobile(string $formId, string $mobilePhone): void
{
$this->client->findElement(WebDriverBy::id(sprintf('%s_tpay_visa_mobile_phone_number', $formId)))->sendKeys($mobilePhone);
}

public function findElementByXpath(string $xpath): WebDriverElement
{
return $this->client->findElement(WebDriverBy::xpath($xpath));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ public function test_it_leaves_google_pay_token_field_once_google_pay_token_is_s
$form->remove('blik_token')->shouldBeCalled()->willReturn($form);
$form->remove('google_pay_token')->shouldNotBeCalled();
$form->remove('tpay_channel_id')->shouldBeCalled()->willReturn($form);
$form->remove('visa_mobile_phone_number')->shouldBeCalled()->willReturn($form);


$event = new FormEvent($form->reveal(), ['google_pay_token' => '123456']);

Expand Down Expand Up @@ -74,6 +76,7 @@ public function test_it_leaves_visa_mobile_field_once_visa_mobile_is_set(): void
$form = $this->prophesize(FormInterface::class);
$form->remove('card')->shouldBeCalled()->willReturn($form);
$form->remove('blik_token')->shouldBeCalled()->willReturn($form);
$form->remove('google_pay_token')->shouldBeCalled()->willReturn($form);
$form->remove('tpay_channel_id')->shouldBeCalled()->willReturn($form);
$form->remove('visa_mobile_phone_number')->shouldNotBeCalled();

Expand Down
3 changes: 2 additions & 1 deletion translations/validators.en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,6 @@ commerce_weavers_sylius_tpay:
name: 'The cardholder name is required.'
visa_mobile:
required: 'The mobile phone number is required.'
min_length: 'The mobile phone must be composed minimum of 9 digits.'
min_length: 'The mobile phone must be composed minimum of 7 digits.'
max_length: 'The mobile phone must be composed maximum of 15 digits.'
regex: 'The mobile phone must consist only of digits.'
3 changes: 2 additions & 1 deletion translations/validators.pl.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,6 @@ commerce_weavers_sylius_tpay:
name: 'Imię i nazwisko właściciela karty są wymagane.'
visa_mobile:
required: 'Numer telefonu jest wymagany.'
min_length: 'Numer telefonu musi składać się z minimum 9 cyfr.'
min_length: 'Numer telefonu musi składać się z minimum 7 cyfr.'
max_length: 'Numer telefonu musi składać się z maksimum 15 cyfr.'
regex: 'Numer telefonu musi składać się tylko z cyfr.'

0 comments on commit 218e2b7

Please sign in to comment.