Skip to content

Instantly share code, notes, and snippets.

@mazyvan
Created May 11, 2018 22:30
Show Gist options
  • Save mazyvan/26ec227e9516e522a394f47c3d75893a to your computer and use it in GitHub Desktop.
Save mazyvan/26ec227e9516e522a394f47c3d75893a to your computer and use it in GitHub Desktop.
An old school random code generator in php
<?php
namespace App\Helpers;
use \Exception;
class RandomCode
{
/**
* La longitud de caracteres que tendrán los códigos
*
* @var int
*/
protected $length = 8;
/**
* El prefijo que usaran los códigos
*
* @var string
*/
protected $prefix = "";
/**
* El alfabeto que usaran los códigos
*
* @var string
*/
protected $alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-";
/**
* Crea una nueva instancia de RandomCode.
*
* @param int $length (optional)
* @param array $options [prefix]
* @return RandomCode
*/
public function __construct($length = null, $options = [])
{
foreach ($options as $key => $value) {
$this->{$key} = $value;
}
if ($length) $this->length = intval($length);
}
/**
* Cambia el valor de la variable $length
*
* @param int $newLength
* @return void
*/
public function setLength($newLength)
{
$this->length = (int) $newLength;
}
/**
* Cambia el valor de la variable $prefix
*
* @param string $newPrefix
* @return void
*/
public function setPrefix($newPrefix)
{
$this->prefix = (string) $newPrefix;
}
/**
* Cambia el alfabeto de caracteres permitidos
*
* @param string $newAlphabet
* @return void
*/
public function setAlphabet($newAlphabet)
{
$this->alphabet = (string) $newAlphabet;
}
/**
* Regresa un código aleatorio de n dígitos del alfabeto de caracteres
*
* @param string $alphabet
* @param int $length
* @param string $prefix
* @return string
*/
private static function generateOne($alphabet, $length, $prefix)
{
$random_code = "";
for ($i = 0; $i < $length; $i++) {
$random_code .= substr($alphabet, random_int(0, strlen($alphabet) - 1), 1);
}
return $prefix.$random_code;
}
/**
* Regresa x códigos aleatorios no repetidos de n dígitos del alfabeto de
* caracteres
*
* @param string $alphabet
* @param int $length
* @param string $prefix
* @param int $quantity
* @param int $left (optional)
* @param string[] $result (optional)
* @return string
*/
private static function generateMany($alphabet, $length, $prefix, $quantity, $left = null, $result = [])
{
if (!isset($left)) $left == $quantity;
for ($i = 0; $i < $left; $i++) {
array_push($result, self::generateOne($alphabet, $length, $prefix));
}
$result = array_unique($result);
$left = $quantity - count($result);
if ($left == 0) return $result;
else return self::generateMany($alphabet, $length, $prefix, $quantity, $left, $result);
}
/**
* Regresa uno o varios códigos aleatorios de n dígitos ([A-Z0-9\-]+)
*
* @param int $quantity (optional)
* @return string[]|string
*/
public function generate($quantity = 1)
{
$length = (int) $this->length;
$prefix = (string) $this->prefix;
$alphabet = (string) $this->alphabet;
$max_number_of_posible_permutations = pow(strlen($alphabet), $length);
if ($quantity > $max_number_of_posible_permutations) {
throw new Exception("La cantidad de códigos solicitados es mayor que el número máximo de permutaciones posibles.");
}
if ((int) $quantity < 2) return self::generateOne($alphabet, $length, $prefix);
else return self::generateMany($alphabet, $length, $prefix, $quantity);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment