Skip to content

Instantly share code, notes, and snippets.

@medeiroz
Created June 24, 2024 15:21
Show Gist options
  • Save medeiroz/6e4a197fdf38d423d9008223d95e9bc5 to your computer and use it in GitHub Desktop.
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
<?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);
}
}
@medeiroz
Copy link
Author

Usage

<?PHP

try {
    $generator = new ReferenceCodeGenerator();
    $currentCode = '000009';
    $newCode = $generator->increment($currentCode);
    echo $newCode; // Outputs: 00000A
} catch (InvalidArgumentException $e) {
    echo 'Error: ' . $e->getMessage();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment