Created
July 26, 2017 10:32
-
-
Save troelskn/069b1f013be36ad9d1e06a62aa425931 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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