Skip to content

Commit

Permalink
Refactor to take into account key length
Browse files Browse the repository at this point in the history
  • Loading branch information
stevebauman committed Jul 23, 2024
1 parent 5e6b67b commit 06364a3
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions src/Classes/KeyGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use AshAllenDesign\ShortURL\Interfaces\UrlKeyGenerator;
use AshAllenDesign\ShortURL\Models\ShortURL;
use Hashids\Hashids;
use Illuminate\Support\Str;

class KeyGenerator implements UrlKeyGenerator
{
Expand All @@ -30,11 +31,18 @@ public function __construct(Hashids $hashids)
*/
public function generateRandom(): string
{
$ID = $this->getLastInsertedID();
$id = $this->getLastInsertedID();

$keyLength = $this->getKeyLength() - 1;

do {
$ID++;
$key = $this->hashids->encodeHex($ID.uniqid());
$id++;

$key = $this->hashids->encodeHex(
substr(uniqid((string) $id), -$keyLength)
);

$keyLength++;
} while (ShortURL::where('url_key', $key)->exists());

return $key;
Expand All @@ -52,6 +60,14 @@ public function generateKeyUsing(int $seed = null): string
: $this->generateRandom();
}

/**
* Get the minimum length of the Short URL key to generate.
*/
protected function getKeyLength(): int
{
return config('short-url.key_length');
}

/**
* Get the ID of the last inserted ShortURL. This is done so that we can predict
* what the ID of the ShortURL that will be inserted will be called. From doing
Expand Down

0 comments on commit 06364a3

Please sign in to comment.