Skip to content

Instantly share code, notes, and snippets.

@troelskn
Created July 26, 2017 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troelskn/069b1f013be36ad9d1e06a62aa425931 to your computer and use it in GitHub Desktop.
Save troelskn/069b1f013be36ad9d1e06a62aa425931 to your computer and use it in GitHub Desktop.
<?php
class IbanConverter
{
function convert_dk($input) {
// DKkk BBBB CCCC CCCC CC
$iban = "DK00" .
str_pad($input['dk_bank_reg_number'], 4, "0", STR_PAD_LEFT) .
str_pad($input['dk_bank_account_number'], 10, "0", STR_PAD_LEFT);
$this->iban_replace_checksum($iban);
}
protected function iban_replace_checksum($iban) {
$checksum = $this->iban_find_checksum($iban);
return substr($iban, 0, 2) . str_pad($checksum, 2, "0", STR_PAD_LEFT) . substr($iban, 4);
}
protected function iban_find_checksum($iban) {
$iban = $this->iban_to_machine_format($iban);
// move first 4 chars to right
$left = substr($iban, 0, 2) . '00'; // but set right-most 2 (checksum) to '00'
$right = substr($iban, 4);
// glue back together
$tmp = $right . $left;
// convert letters using conversion table
$tmp = $this->iban_checksum_string_replace($tmp);
// get mod97-10 output
$checksum = $this->iban_mod97_10($tmp);
return (98 - $checksum);
}
// Convert an IBAN to machine format. To do this, we
// remove IBAN from the start, if present, and remove
// non basic roman letter / digit characters
protected function iban_to_machine_format($iban) {
// Uppercase and trim spaces from left
$iban = ltrim(strtoupper($iban));
// Remove IBAN from start of string, if present
$iban = preg_replace('/^IBAN/', '', $iban);
// Remove all non basic roman letter / digit characters
$iban = preg_replace('/[^A-Z0-9]/', '', $iban);
return $iban;
}
// Character substitution required for IBAN MOD97-10 checksum validation/generation
// $s Input string (IBAN)
protected function iban_checksum_string_replace($s) {
$iban_replace_chars = range('A', 'Z');
foreach (range(10, 35) as $tempvalue) {
$iban_replace_values[] = strval($tempvalue);
}
return str_replace($iban_replace_chars, $iban_replace_values, $s);
}
// Perform MOD97-10 checksum calculation
// $s Input string (IBAN)
protected function iban_mod97_10($s) {
$tr = intval(substr($s, 0, 1));
for ($pos = 1; $pos < strlen($s); $pos++) {
$tr *= 10;
$tr += intval(substr($s, $pos, 1));
$tr %= 97;
}
return $tr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment