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
Iban.php
74 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Faker\Calculator; |
| 4 | |
| 5 | class Iban |
| 6 | { |
| 7 | /** |
| 8 | * Generates IBAN Checksum |
| 9 | * |
| 10 | * @param string $iban |
| 11 | * @return string Checksum (numeric string) |
| 12 | */ |
| 13 | public static function checksum($iban) |
| 14 | { |
| 15 | // Move first four digits to end and set checksum to '00' |
| 16 | $checkString = substr($iban, 4) . substr($iban, 0, 2) . '00'; |
| 17 | |
| 18 | // Replace all letters with their number equivalents |
| 19 | $checkString = preg_replace_callback('/[A-Z]/', array('self','alphaToNumberCallback'), $checkString); |
| 20 | |
| 21 | // Perform mod 97 and subtract from 98 |
| 22 | $checksum = 98 - self::mod97($checkString); |
| 23 | |
| 24 | return str_pad($checksum, 2, '0', STR_PAD_LEFT); |
| 25 | } |
| 26 | |
| 27 | /** |
| 28 | * @param string $match |
| 29 | * |
| 30 | * @return int |
| 31 | */ |
| 32 | private static function alphaToNumberCallback($match) |
| 33 | { |
| 34 | return self::alphaToNumber($match[0]); |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * Converts letter to number |
| 39 | * |
| 40 | * @param string $char |
| 41 | * @return int |
| 42 | */ |
| 43 | public static function alphaToNumber($char) |
| 44 | { |
| 45 | return ord($char) - 55; |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * Calculates mod97 on a numeric string |
| 50 | * |
| 51 | * @param string $number Numeric string |
| 52 | * @return int |
| 53 | */ |
| 54 | public static function mod97($number) |
| 55 | { |
| 56 | $checksum = (int)$number[0]; |
| 57 | for ($i = 1, $size = strlen($number); $i < $size; $i++) { |
| 58 | $checksum = (10 * $checksum + (int) $number[$i]) % 97; |
| 59 | } |
| 60 | return $checksum; |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Checks whether an IBAN has a valid checksum |
| 65 | * |
| 66 | * @param string $iban |
| 67 | * @return boolean |
| 68 | */ |
| 69 | public static function isValid($iban) |
| 70 | { |
| 71 | return self::checksum($iban) === substr($iban, 2, 2); |
| 72 | } |
| 73 | } |
| 74 |