thewebsolver/luhn-algorithm

PHP库,用于使用Luhn算法验证信用卡号、IMEI号码等数字

dev-main 2024-09-12 14:01 UTC

This package is auto-updated.

Last update: 2024-09-12 14:01:31 UTC


README

📦 此软件包是正在开发中的PHP验证器的一个子仓库。

✨ 它也可以作为Payment Card库的依赖项安装,以验证借记/信用卡。

简介

Luhn算法,用于验证支付卡、IMEI号码和其他需要Luhn验证的数字。

用法

安装

composer require thewebsolver/luhn-algorithm

验证

验证可以使用以下三种选项中的任何一种进行

use TheWebSolver\Codegarage\LuhnAlgorithm;

// OPTION 1: Value passing via constructor.
$luhn     = new LuhnAlgorithm(79927398713);
$isValid  = $luhn->isValid();  // true
$checksum = $luhn->checksum(); // 70

// OPTION 2: Value passing via invocable class.
$luhn     = new LuhnAlgorithm();
$isValid  = $luhn(79927398713); // true
$checksum = $luhn->checksum();  // 70

// OPTION 3: Value passing via static method. In this case, There is no
// instance stored in memory & can only be used for one-off validation.
$isValid = LuhnAlgorithm::validate(79927398713); // true

调试

从上面的验证示例中,我们可以调试更多关于验证状态和计算校验和时每个数字的各种状态的详细信息。

var_dump( $luhn ); // Input value was: 79927398713

// The debug output.
array(4) {
  'isValid' =>
  bool(true)
  'digits' =>
  int(79947697723)
  'checksum' =>
  int(70)
  'state' =>
  array(11) {
    [0] =>
    array(2) {
      'doubled' =>
      bool(false)
      'result' =>
      int(7)
    }
    [1] =>
    array(2) {
      'doubled' =>
      bool(true)
      'result' =>
      int(9)
    }
    [2] =>
    array(2) {
      'doubled' =>
      bool(false)
      'result' =>
      int(9)
    }
    [3] =>
    array(2) {
      'doubled' =>
      bool(true)
      'result' =>
      int(4)
    }
    [4] =>
    array(2) {
      'doubled' =>
      bool(false)
      'result' =>
      int(7)
    }
    [5] =>
    array(2) {
      'doubled' =>
      bool(true)
      'result' =>
      int(6)
    }
    [6] =>
    array(2) {
      'doubled' =>
      bool(false)
      'result' =>
      int(9)
    }
    [7] =>
    array(2) {
      'doubled' =>
      bool(true)
      'result' =>
      int(7)
    }
    [8] =>
    array(2) {
      'doubled' =>
      bool(false)
      'result' =>
      int(7)
    }
    [9] =>
    array(2) {
      'doubled' =>
      bool(true)
      'result' =>
      int(2)
    }
    [10] =>
    array(2) {
      'doubled' =>
      bool(false)
      'result' =>
      int(3)
    }
  }
}

组成

Luhn Algorithm 类实际上是通过使用 Luhn 特性来组成的。这个特性可以在你的项目中定义的其他类中使用,或者根据项目的需求修改验证方法(尽管后者似乎并不必要)。