Skip to content

Instantly share code, notes, and snippets.

@AleksandrMihhailov
Last active February 24, 2017 09:25
Show Gist options
  • Save AleksandrMihhailov/2a5e7d85894b539c993fe0fe1177084a to your computer and use it in GitHub Desktop.
Save AleksandrMihhailov/2a5e7d85894b539c993fe0fe1177084a to your computer and use it in GitHub Desktop.
Alphabet and numbers key generator
<?php
class AlphaKeyGen {
private $length;
private $alphaData, $key = [];
public function __construct($length = 5) {
$this->length = $length;
$this->alphaData = array_merge(
range('a', 'z'),
range(0, 9)
);
}
public function next() {
if (!count($this->key)) $this->initKey();
else $this->initNew();
return $this;
}
public function set($key = null) {
if (!is_null($key)) {
$this->key = str_split($key);
$this->length = count($this->key);
}
return $this;
}
public function get() {
return implode('', $this->key);
}
private function initKey() {
for ($i = 0; $i < $this->length; ++$i) {
$this->key[] = $this->alphaData[0];
}
}
private function initNew() {
for ($i = $this->length - 1; $i >= 0; --$i) {
$currentKey = array_search(
$this->key[$i],
$this->alphaData
);
if ($currentKey === (count($this->alphaData) - 1)) {
$this->key[$i] = $this->alphaData[0];
}
if ($currentKey < (count($this->alphaData) - 1)) {
$this->key[$i] = $this->alphaData[$currentKey + 1];
break;
}
}
}
}
// example
echo (new AlphaKeyGen)->set()->next()->get()."\n"; // result: aaaaa
echo (new AlphaKeyGen)->set('aaaaa')->next()->get()."\n"; // result: aaaab
echo (new AlphaKeyGen)->set('aaaa9')->next()->get()."\n"; // result: aaaba
echo (new AlphaKeyGen)->set('8999999')->next()->get()."\n"; // result: 9aaaaaa
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment