Created
June 24, 2024 15:21
-
-
Save medeiroz/6e4a197fdf38d423d9008223d95e9bc5 to your computer and use it in GitHub Desktop.
PHP Reference Code Generator with Custom Base. Increment 0-9 A-Z alphanumeric
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 ReferenceCodeGenerator { | |
private readonly int $base; | |
public function __construct( | |
private readonly int $codeLength = 6, | |
private readonly string $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', | |
) { | |
$this->base = strlen($this->characters); | |
} | |
/** | |
* Increment the given reference code. | |
* | |
* @param string $currentCode The current reference code to be incremented. | |
* @return string The incremented reference code. | |
* @throws InvalidArgumentException If the current code is not valid. | |
*/ | |
public function increment(string $currentCode): string | |
{ | |
$this->validateCode($currentCode); | |
$currentInt = $this->convertToInteger($currentCode); | |
$currentInt++; | |
return $this->convertToCustomBase($currentInt); | |
} | |
/** | |
* Validate the reference code. | |
* | |
* @param string $code The code to be validated. | |
* @throws InvalidArgumentException If the code is not valid. | |
*/ | |
private function validateCode(string $code): void | |
{ | |
if (strlen($code) !== $this->codeLength) { | |
throw new InvalidArgumentException('Invalid code length.'); | |
} | |
if (!preg_match('/^[0-9A-Z]+$/', $code)) { | |
throw new InvalidArgumentException('Code contains invalid characters.'); | |
} | |
} | |
/** | |
* Convert a custom base code to an integer. | |
* | |
* @param string $code The code to be converted. | |
* @return int The converted integer. | |
*/ | |
private function convertToInteger(string $code): int | |
{ | |
$length = strlen($code); | |
$currentInt = 0; | |
for ($i = 0; $i < $length; $i++) { | |
$currentInt = $currentInt * $this->base + strpos($this->characters, $code[$i]); | |
} | |
return $currentInt; | |
} | |
/** | |
* Convert an integer to a custom base code. | |
* | |
* @param int $int The integer to be converted. | |
* @return string The converted custom base code. | |
*/ | |
private function convertToCustomBase(int $int): string | |
{ | |
$newCode = ''; | |
while ($int > 0) { | |
$newCode = $this->characters[$int % $this->base] . $newCode; | |
$int = intdiv($int, $this->base); | |
} | |
return str_pad($newCode, $this->codeLength, '0', STR_PAD_LEFT); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage