Skip to content

Instantly share code, notes, and snippets.

@szihaj
Created April 6, 2018 11:19
Show Gist options
  • Save szihaj/cbabb30c9deb1e033eb097eae76129ec to your computer and use it in GitHub Desktop.
Save szihaj/cbabb30c9deb1e033eb097eae76129ec to your computer and use it in GitHub Desktop.
Hungarian tax number generator
<?php
namespace Acme\Utilities;
use \DateTime;
class HungarianTaxNumberGenerator
{
protected $number = '8';
protected $birthDate;
protected $baseDate = '1867-01-01';
protected $random;
public function __construct($birthDate, $random = null)
{
$this->birthDate = $birthDate;
if ( ! is_null($random)) {
$this->random = $random;
} else {
$this->random = $this->getRandom();
}
}
public function generate()
{
$this->number .= $this->getDateDiff();
$this->number .= $this->random;
$this->number .= $this->calcLastDigit();
return substr($this->number, 0, 10);
}
protected function getDateDiff()
{
try {
$baseDate = new DateTime($this->baseDate);
$birthDate = new DateTime($this->birthDate);
} catch (Exception $e) {
echo $e->getMessage();
return false;
}
return $birthDate->diff($baseDate)->format("%a");
}
public function getRandom()
{
return str_pad(mt_rand(0, 999), 3, '0', STR_PAD_LEFT);
}
protected function calcLastDigit()
{
$multiplications = [];
for ($i = 0; $i < strlen($this->number); $i ++) {
$multiplications[] = (int)$this->number[$i] * ($i + 1);
}
return array_sum($multiplications) % 11;
}
}
// $generator = new HungarianTaxNumberGenerator('1970-09-11');
// echo $generator->generate();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment