Skip to content

Instantly share code, notes, and snippets.

@farindra
Created December 12, 2019 13:05
Show Gist options
  • Save farindra/6334d97d160c582f91623cc8aac95ebd to your computer and use it in GitHub Desktop.
Save farindra/6334d97d160c582f91623cc8aac95ebd to your computer and use it in GitHub Desktop.
class CodeGenerator {
public static $baseCharacters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static function increment($x, $digits)
{
$charList = static::$baseCharacters;
// completa cadeia de caracteres com o numero de digitos parametrizados
$x = trim($x);
if(strlen($x) < $digits) {
$x = str_pad($x, $digits, substr($charList, 0, 1), STR_PAD_LEFT);
}
$result = preg_split("//", $x, -1, PREG_SPLIT_NO_EMPTY);
// percorre a cadeia de caracteres de tras pra frente e incrementa o primeiro caractere possivel
for ($i = $digits - 1; $i >= 0; --$i)
{
$char = $result[$i];
$currentChar = strpos($charList, $char);
$nextCharPosition = $currentChar+1;
if($nextCharPosition < strlen($charList)) {
$nextChar = substr($charList, $nextCharPosition, 1);
$result[$i] = $nextChar;
break;
}
}
return implode('', $result);
}
public static function decrement($x, $digits)
{
$charList = static::$baseCharacters;
// completa cadeia de caracteres com o numero de digitos parametrizados
if(strlen($x) < $digits) {
$x = str_pad($x, $digits, substr($charList, 0, 1), STR_PAD_LEFT);
}
$result = preg_split("//", $x, -1, PREG_SPLIT_NO_EMPTY);
// percorre a cadeia de caracteres de tras pra frente e decrementa o primeiro caractere possivel
for ($i = $digits - 1; $i >= 0; --$i)
{
$char = $result[$i];
$currentChar = strpos($charList, $char);
$previousCharPosition = $currentChar-1;
if($previousCharPosition > -1) {
$previousChar = substr($charList, $previousCharPosition, 1);
$result[$i] = $previousChar;
// define os caracteres apos o decrementado para o ultimo caractere. ex: 3[00] > 2[99]
for ($j = $i + 1; $j < $digits && $i < $digits - 1; ++$j)
$result[$j] = substr($charList, strlen($charList)-1, 1);
break;
}
}
return implode('', $result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment