Add baseuaen.php
This commit is contained in:
56
baseuaen.php
Normal file
56
baseuaen.php
Normal file
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
class BaseUAEN
|
||||
{
|
||||
private const CHARACTERS = 'ABCEHKMOPTXY'; // Characters valid in both English and Ukrainian
|
||||
private const MIN_LENGTH = 4;
|
||||
private const MAX_LENGTH = 8;
|
||||
|
||||
public function intToCode(int $number, int $length): string
|
||||
{
|
||||
if ($length < self::MIN_LENGTH || $length > self::MAX_LENGTH) {
|
||||
throw new InvalidArgumentException("Length must be between " . self::MIN_LENGTH . " and " . self::MAX_LENGTH);
|
||||
}
|
||||
|
||||
$base = strlen(self::CHARACTERS);
|
||||
$code = '';
|
||||
|
||||
do {
|
||||
$remainder = $number % $base;
|
||||
$code = self::CHARACTERS[$remainder] . $code;
|
||||
$number = intdiv($number, $base);
|
||||
} while ($number > 0);
|
||||
|
||||
return str_pad($code, $length, self::CHARACTERS[0], STR_PAD_LEFT);
|
||||
}
|
||||
|
||||
public function codeToInt(string $code): int
|
||||
{
|
||||
$base = strlen(self::CHARACTERS);
|
||||
$length = strlen($code);
|
||||
$number = 0;
|
||||
|
||||
for ($i = 0; $i < $length; $i++) {
|
||||
$char = $code[$i];
|
||||
$charIndex = strpos(self::CHARACTERS, $char);
|
||||
if ($charIndex === false) {
|
||||
throw new InvalidArgumentException("Invalid character in code");
|
||||
}
|
||||
$number = $number * $base + $charIndex;
|
||||
}
|
||||
|
||||
return $number;
|
||||
}
|
||||
|
||||
public function generateRandomInt(int $length): int
|
||||
{
|
||||
if ($length < self::MIN_LENGTH || $length > self::MAX_LENGTH) {
|
||||
throw new InvalidArgumentException("Length must be between " . self::MIN_LENGTH . " and " . self::MAX_LENGTH);
|
||||
}
|
||||
|
||||
$base = strlen(self::CHARACTERS);
|
||||
$maxNumber = bcpow($base, $length) - 1;
|
||||
|
||||
return random_int(0, $maxNumber);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user