Skip to content
Shesh Ghimire edited this page Sep 14, 2024 · 4 revisions

📦 This Payment Card package is a sub-repo split of a PHP Validator which is currently under development.

Welcome

This package can be used to validate various Payment Cards such as Debit/Credit Card. For more flexibility, the Luhn validation is not enforced by default but can easily be incorporated with first-party package.

If Luhn Algorithm package is not installed, the Luhn validation is skipped. Meaning the Card Number will never be checked against Luhn Algorithm and will always pass the Luhn Validation.

Features

  • Enum Cases: Common Payment Cards
  • Card Interface: Contract to create implementation of Payment Card
  • Factory: Card Factory to create Payment Cards on demand from an array, a PHP file, or a JSON file (recommended)
  • CardType: Abstract class to be extended by any named PHP class. Eg: test Napas Card
  • Traits: Promote composition over inheritance for maximum flexibility and fluent Developer Experience

Quick Setup

Installation

composer require thewebsolver/payment-card

To use Luhn validation using the first-party package:

composer require thewebsolver/luhn-algorithm

Bootstrap

To validate Payment Card, either using defaults or from your Payment Cards defined in a JSON file, we first need to define a class that uses Card Resolver.

In the first-party PHP Validator package (currently in development and unfortunately not available), this is provided as a validation rule and you do not need to manually create your own class.

For more details, check default Payment Cards with Schema defined in a JSON file as well as other test files example.

namespace App\Validation;

use TheWebSolver\Codegarage\PaymentCard\CardInterface;
use TheWebSolver\Codegarage\PaymentCard\Traits\CardResolver;

class CardValidator {
    use CardResolver;

    public function __construct( bool $disableDefaultPaymentCards = false ) {
        $payload = 'path/to/allowedCards.json';

        $this->registerCardsFromPayload( data: $payload );

        // Filter whether default Payment Cards should be used or not. If only Payment Cards defined
        // in your payload file are allowed for validation, then disable it on the Card Resolver.
        if ( $disableDefaultPaymentCards ) {
            $this->withoutDefaults();
        }
    }

    public function validate( string|int $cardNumber ): bool {
        $resolvedCard = $this->resolveCardFromNumber( (string) $cardNumber );

        return $resolvedCard instanceof CardInterface;
    }
}

Usage

After bootstrapping your custom validator class, use newly created CardValidator class in your application where applicable.

use App\Validation\CardValidator;

$cardValidator   = new CardValidator();
$americanExpress = 378282246310005;
$isValidCard     = $cardValidator->validate(cardNumber: $americanExpress); // true
Clone this wiki locally