Skip to content

Instantly share code, notes, and snippets.

@Cleanse
Created July 13, 2017 16:19
Show Gist options
  • Save Cleanse/381de1c3a7e7ecb4acf5d7f5555c7796 to your computer and use it in GitHub Desktop.
Save Cleanse/381de1c3a7e7ecb4acf5d7f5555c7796 to your computer and use it in GitHub Desktop.
<?php namespace Cleanse\Urls\Classes;
use ApplicationException;
class ShortIds
{
public $radix;
public $words;
public function __construct()
{
$numbers = range(0, 9);
$letters = range('a', 'z');
$special = ['$', '-', '_', '+', '!', '*', '(', ')', ','];
$this->radix = array_merge($numbers, $letters, $special);
$filename = './plugins/cleanse/urls/assets/csv/words.csv';
if (file_exists($filename)) {
$this->words = array_map('str_getcsv', file($filename));
} else {
throw new ApplicationException('Cannot find .csv file.');
}
}
public function newShorty($model, $max_len = 8)
{
$max = pow(count($this->radix), $max_len);
do {
$id = rand(1, $max);
$newId = $this->radixToString($id);
$exists = $model::where('id', '=', $newId)->first();
} while (!in_array($id, $this->words) && $exists);
return $newId;
}
public function radixToString($value)
{
$base = count($this->radix);
if ($base < 2) {
throw new ApplicationException('radix must have at least two digits.');
}
$i = intval($value);
$out = [];
while ($i > 0) {
$i = floor($i/$base);
$remainder = $i % $base;
$out[] = $this->radix[$remainder];
}
return implode('', $out);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment