Skip to content

Instantly share code, notes, and snippets.

@aaronfc
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save aaronfc/4e9a88db13ef99824048 to your computer and use it in GitHub Desktop.

Select an option

Save aaronfc/4e9a88db13ef99824048 to your computer and use it in GitHub Desktop.
Create IBAN from bank account in PHP
<?php
/**
* BankAccountConverter class
*
* @author aaronfc <[email protected]>
*/
class BankAccountConverter {
/**
* Static constructor
* @return BankAccountConverter
*/
public static function create() {
return new static();
}
/**
* Get a bank account as a plain string and a country code and returns its IBAN equivalent.
* @param string $fullBankAccount
* @return string
*/
public function toIban($fullBankAccount, $countryCode) {
$checksum = $this->calculateChecksum($fullBankAccount, $countryCode);
return $countryCode . $checksum . $fullBankAccount;
}
/**
* Calculates checksum for a given bank account and its country code.
* @param $fullBankAccount
* @param string $countryCode
* @return string
*/
private function calculateChecksum($fullBankAccount, $countryCode)
{
$asArray = str_split(strtoupper($fullBankAccount . str_pad($countryCode, 4 , "0")));
$numeric = array_map(array($this, "castAlphabeticCharToEquivalentNumber"), $asArray);
$numeric = join('', $numeric);
// bcmod used because regular mod operator can't handle such a big number (overflowed int)
return str_pad(98 - bcmod($numeric,97), 2, "0", STR_PAD_LEFT);
}
/**
* Cast alphabetic character to number as required by IBAN generation algorithm.
* Thus: A=10, B=11, ... Z=35
*
* @param $char
* @return int
*/
private function castAlphabeticCharToEquivalentNumber($char) {
if (ctype_alpha($char)){
return ord($char) - 55;
}
return $char;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment