Ean.php
5 years ago
Iban.php
5 years ago
Inn.php
5 years ago
Luhn.php
5 years ago
TCNo.php
5 years ago
Luhn.php
76 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Faker\Calculator; |
| 4 | |
| 5 | use InvalidArgumentException; |
| 6 | |
| 7 | /** |
| 8 | * Utility class for generating and validating Luhn numbers. |
| 9 | * |
| 10 | * Luhn algorithm is used to validate credit card numbers, IMEI numbers, and |
| 11 | * National Provider Identifier numbers. |
| 12 | * |
| 13 | * @see http://en.wikipedia.org/wiki/Luhn_algorithm |
| 14 | */ |
| 15 | class Luhn |
| 16 | { |
| 17 | /** |
| 18 | * @param string $number |
| 19 | * @return int |
| 20 | */ |
| 21 | private static function checksum($number) |
| 22 | { |
| 23 | $number = (string) $number; |
| 24 | $length = strlen($number); |
| 25 | $sum = 0; |
| 26 | for ($i = $length - 1; $i >= 0; $i -= 2) { |
| 27 | $sum += $number[$i]; |
| 28 | } |
| 29 | for ($i = $length - 2; $i >= 0; $i -= 2) { |
| 30 | $sum += array_sum(str_split($number[$i] * 2)); |
| 31 | } |
| 32 | |
| 33 | return $sum % 10; |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * @param $partialNumber |
| 38 | * @return string |
| 39 | */ |
| 40 | public static function computeCheckDigit($partialNumber) |
| 41 | { |
| 42 | $checkDigit = self::checksum($partialNumber . '0'); |
| 43 | if ($checkDigit === 0) { |
| 44 | return 0; |
| 45 | } |
| 46 | |
| 47 | return (string) (10 - $checkDigit); |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * Checks whether a number (partial number + check digit) is Luhn compliant |
| 52 | * |
| 53 | * @param string $number |
| 54 | * @return bool |
| 55 | */ |
| 56 | public static function isValid($number) |
| 57 | { |
| 58 | return self::checksum($number) === 0; |
| 59 | } |
| 60 | |
| 61 | /** |
| 62 | * Generate a Luhn compliant number. |
| 63 | * |
| 64 | * @param string $partialValue |
| 65 | * |
| 66 | * @return string |
| 67 | */ |
| 68 | public static function generateLuhnNumber($partialValue) |
| 69 | { |
| 70 | if (!preg_match('/^\d+$/', $partialValue)) { |
| 71 | throw new InvalidArgumentException('Argument should be an integer.'); |
| 72 | } |
| 73 | return $partialValue . Luhn::computeCheckDigit($partialValue); |
| 74 | } |
| 75 | } |
| 76 |