Skip to content

Commit d51586a

Browse files
committed
Added Hashsids
Added Hashids to create Short URLs based on the current primary key of the urls table. This way is SURE Short URLs wll alway be unique, but the check is made anyway because we allow custom short urls also.
1 parent 3fa8692 commit d51586a

File tree

3 files changed

+94
-3
lines changed

3 files changed

+94
-3
lines changed

app/Services/UrlService.php

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
use App\User;
1414
use App\Url;
1515
use Auth;
16+
use Hashids\Hashids;
1617
use Illuminate\Support\Str;
1718

1819

@@ -45,14 +46,36 @@ public function shortenUrl($long_url, $short_url, $privateUrl, $hideUrlStats)
4546

4647
// Iterate until a not-already-created short url is generated
4748
do {
48-
$short_url = Str::random(6);
49-
// ! because we need 'false', not 'true'
49+
$short_url = $this->generateShortUrl();
5050
} while ($this->customUrlExisting($short_url));
5151

5252
Url::createShortUrl($long_url, $short_url, $privateUrl, $hideUrlStats);
5353
return $short_url;
5454
}
5555

56+
/**
57+
* Generate an unique short URL using hashids. Salt is the APP_KEY, which is always unique
58+
*
59+
* @return string
60+
*/
61+
public function generateShortUrl()
62+
{
63+
$hashids = new Hashids(env('APP_KEY'), 4);
64+
65+
$current = Url::orderBy('id', 'desc')->lockForUpdate()->first();
66+
67+
// If this is the first Short URL, let's encode a 0
68+
if ($current === null) {
69+
return $hashids->encode(0);
70+
}
71+
72+
$currentInc = $current->id;
73+
$currentInc++;
74+
75+
return $hashids->encode($currentInc);
76+
}
77+
78+
5679
/**
5780
* Check if is possible to use the Custom URL or not
5881
*

composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"fideloper/proxy": "^4.0",
1616
"geoip2/geoip2": "~2.0",
1717
"guzzlehttp/guzzle": "^6.3",
18+
"hashids/hashids": "^4.0",
1819
"laravel-frontend-presets/argon": "^1.0",
1920
"laravel/framework": "5.8.*",
2021
"laravel/tinker": "^1.0",

composer.lock

Lines changed: 68 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)