Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Helpers;
- use Hashids\Hashids;
- use Illuminate\Support\Facades\Route;
- class UrlShortener
- {
- private $hashids;
- private $bannedWords;
- public function __construct()
- {
- $this->hashids = new Hashids(config('app.url_shortener_salt'), 6);
- $this->bannedWords = $this->getBannedWords();
- }
- public function encode($url)
- {
- do {
- $prefix = substr(md5($url), 0, 2); // Generate a 2-character prefix from MD5
- $suffix = substr(sha1($url), -2); // Generate a 2-character suffix from SHA1
- $id = crc32($url);
- $hash = $this->hashids->encode($id);
- $shortUrl = $prefix . $hash . $suffix; // Combine prefix, hash, and suffix
- } while ($this->isBannedWord($shortUrl));
- return $shortUrl;
- }
- private function getBannedWords()
- {
- $bannedWords = [];
- $routes = Route::getRoutes();
- foreach ($routes as $route) {
- $uri = $route->uri();
- if (!in_array($uri, $bannedWords)) {
- $bannedWords[] = $uri;
- }
- }
- return $bannedWords;
- }
- private function isBannedWord($shortUrl)
- {
- return in_array($shortUrl, $this->bannedWords);
- }
- public function decode($hash)
- {
- $prefix = substr($hash, 0, 2);
- $suffix = substr($hash, -2);
- $hash = substr($hash, 2, -2);
- $decoded = $this->hashids->decode($hash);
- if (!empty($decoded)) {
- $urlId = $decoded[0];
- // Verify the prefix and suffix by calculating them again
- if ($prefix === substr(md5($urlId), 0, 2) && $suffix === substr(sha1($urlId), -2)) {
- return $urlId;
- }
- }
- return null;
- }
- }
Advertisement
Advertisement