/src/Faker/Calculator/Iban.php

https://github.com/fzaninotto/Faker · PHP · 73 lines · 32 code · 9 blank · 32 comment · 1 complexity · 117e66b10692f93c0c463206e38b347f MD5 · raw file

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