PHP code example of ccgenerator / test-cards

1. Go to this page and download the library: Download ccgenerator/test-cards library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ccgenerator / test-cards example snippets


use CCGenerator\TestCards\TestCards;

$card = TestCards::generate('mastercard');

$card->pan;          // "5393016145498473"
$card->formatted();  // "5393 0161 4549 8473"
$card->cvv;          // "695"
$card->expiry();     // "09/30"

TestCards::detectBrand('2223 0031 2200 3222')->value;  // "mastercard"
TestCards::validate('4111111111111112')->errors;       // ["luhn_failed"]

use CCGenerator\TestCards\Brand;
use CCGenerator\TestCards\TestCards;

// One card, random network
$card = TestCards::generate();

// A specific network — string or enum, whichever suits the caller
TestCards::generate('amex');
TestCards::generate(Brand::Amex);

// A length that network actually issues
TestCards::generate('maestro', length: 19);

// A batch for a data provider
$cards = TestCards::many(100, 'visa');

// One of every network: 14, 15, 16 and 19 digits, 3 and 4-digit CVVs
$corpus = TestCards::oneOfEach();

// A number that looks right and fails the checksum
$typo = TestCards::invalid('visa');

// Structural validation
$result = TestCards::validate('4111 1111 1111 1111');
$result->valid;        // true
$result->brand;        // Brand::Visa
$result->errors;       // []

// config/test-cards.php
return [
    'seed' => env('TEST_CARDS_SEED'),   // null = fresh numbers every run
    'expiry_years_ahead' => 5,
    'accepted_networks' => [],          // [] = every network in the table
];

use TestCards;                                  // the facade alias
use CCGenerator\TestCards\CardService;          // or inject the service

class CheckoutSeeder
{
    public function __construct(private CardService $cards) {}

    public function run(): void
    {
        $card = $this->cards->generate('visa');
        // ...
    }
}

TestCards::generate('amex');
TestCards::many(50);
TestCards::validate($request->input('card_number'));

TestCards::shouldReceive('generate')->andReturn($knownFixture);

$request->validate([
    'card_number' => 'mex',
    'either'      => '

use CCGenerator\TestCards\Laravel\Rules\TestCardNumber;

$request->validate([
    'card_number' => ['number: structure yes, checksum no
    'on_file'     => ['

// database/factories/PaymentMethodFactory.php
public function definition(): array
{
    return [
        'brand'        => fake()->testCardBrand(),        // "visa"
        'number'       => fake()->testCardNumber('visa'), // Luhn-valid PAN
        'display'      => fake()->testCardNumberFormatted('amex'),
        'cvv'          => fake()->testCardCvv('amex'),    // 4 digits, correctly
        'expires_at'   => fake()->testCardExpiry(),       // "09/29"
    ];
}

use CCGenerator\TestCards\TestCards;

it('accepts every network we settle', function (string $pan) {
    $this->postJson('/checkout', ['card_number' => $pan])
        ->assertSuccessful();
})->with(fn () => collect(TestCards::oneOfEach())->pluck('pan')->all());

it('rejects a mistyped digit', function () {
    $this->postJson('/checkout', ['card_number' => TestCards::invalid('visa')])
        ->assertJsonValidationErrorFor('card_number');
});

public static function cardNumbers(): array
{
    return array_map(
        static fn ($card) => [$card->brand->value, $card->pan],
        TestCards::many(100),
    );
}

#[DataProvider('cardNumbers')]
public function testTheInputMaskSurvivesEveryNetwork(string $network, string $pan): void
{
    $this->assertSame($pan, str_replace(' ', '', formatCardInput($pan)));
}

$cards = CardService::seeded(1337);
$cards->generate('visa')->pan;  // the same number, forever

// config/bundles.php
return [
    // ...
    CCGenerator\TestCards\Symfony\CCGeneratorTestCardsBundle::class => ['dev' => true, 'test' => true],
];

use CCGenerator\TestCards\CardService;
use CCGenerator\TestCards\CardValidator;

final class CheckoutFixtures
{
    public function __construct(
        private readonly CardService $cards,
        private readonly CardValidator $validator,
    ) {
    }

    public function aVisaCard(): string
    {
        return $this->cards->generate('visa')->pan;
    }
}

use CCGenerator\TestCards\Symfony\Validator\TestCardNumber;
use Symfony\Component\Validator\Constraints as Assert;

final class CheckoutInput
{
    #[Assert\NotBlank]
    #[TestCardNumber(networks: ['visa', 'mastercard'])]
    public string $cardNumber = '';

    // A stored number where the checksum is no longer meaningful
    #[TestCardNumber(

#[TestCardNumber(
    networks: ['visa'],
    message: 'card.number.invalid',       // a translation key works too
)]

$builder->add('cardNumber', TextType::class, [
    'constraints' => [new NotBlank(), new TestCardNumber(networks: ['visa'])],
]);

use CCGenerator\TestCards\CardService;

final class CheckoutControllerTest extends WebTestCase
{
    public function testAcceptsEveryNetworkWeSettle(): void
    {
        $client = static::createClient();
        $cards = static::getContainer()->get(CardService::class);

        foreach ($cards->oneOfEach() as $network => $card) {
            $client->request('POST', '/checkout', ['card_number' => $card->pan]);

            self::assertResponseIsSuccessful($network);
        }
    }
}

$card->brand;            // Brand::Visa (backed enum, ->value is "visa")
$card->pan;              // "4835385157667831"
$card->cvv;              // "204"
$card->expiryMonth;      // "09"
$card->expiryYear;       // "2029"

$card->formatted();      // "4835 3851 5766 7831" — grouped per network
$card->expiry();         // "09/29"
$card->expiry('/', false); // "09/2029"
$card->networkName();    // "Visa"
$card->toArray();        // and it is JsonSerializable and Stringable

$result = TestCards::validate('4111 1111 1111 1111');

$result->valid;      // bool — true only when every check passed
$result->brand;      // Brand|null
$result->pan;        // separators removed
$result->length;     // int
$result->luhn;       // bool
$result->errors;     // list<string>

TestCards::isValid($pan, ['visa', 'mastercard']);  // bool

TestCards::detectBrand('4');      // Brand::Visa — works on partial input
TestCards::detectBrand('22');     // Brand::Mastercard
TestCards::detectBrand('');       // null, not an exception

TestCards::isLuhnValid('4111 1111 1111 1111');  // true
TestCards::luhnCheckDigit('411111111111111');   // "1"

use CCGenerator\TestCards\Networks;

Networks::get('amex')->cvvLength;   // 4
Networks::get('amex')->lengths;     // [15]
Networks::get('maestro')->lengths;  // [16, 19]
Networks::all();                    // array<string, Network>

$cards = CardService::seeded(1337);

$cards->many(50);  // the same 50 numbers, on every machine, forever
bash
php artisan vendor:publish --tag=test-cards-config
bash
php artisan vendor:publish --tag=test-cards-lang
# -> lang/vendor/test-cards/{en,tr}/validation.php
bash
php artisan test-cards:generate                          # one random card
php artisan test-cards:generate visa --count=10
php artisan test-cards:generate maestro --length=19 --format=csv
php artisan test-cards:generate --seed=1337 --count=5    # reproducible
php artisan test-cards:generate amex --format=json

php artisan test-cards:validate "4111 1111 1111 1111"
php artisan test-cards:validate 4111111111111112 --json  # exits 1