Advertisement
saimpot

URL Shortener service w/o DB

Mar 22nd, 2023 (edited)
1,074
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.80 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Helpers;
  4.  
  5. use Hashids\Hashids;
  6. use Illuminate\Support\Facades\Route;
  7.  
  8. class UrlShortener
  9. {
  10.     private $hashids;
  11.     private $bannedWords;
  12.  
  13.     public function __construct()
  14.     {
  15.         $this->hashids = new Hashids(config('app.url_shortener_salt'), 6);
  16.         $this->bannedWords = $this->getBannedWords();
  17.     }
  18.  
  19.     public function encode($url)
  20.     {
  21.         do {
  22.             $prefix = substr(md5($url), 0, 2); // Generate a 2-character prefix from MD5
  23.             $suffix = substr(sha1($url), -2); // Generate a 2-character suffix from SHA1
  24.             $id = crc32($url);
  25.             $hash = $this->hashids->encode($id);
  26.             $shortUrl = $prefix . $hash . $suffix; // Combine prefix, hash, and suffix
  27.         } while ($this->isBannedWord($shortUrl));
  28.  
  29.         return $shortUrl;
  30.     }
  31.  
  32.     private function getBannedWords()
  33.     {
  34.         $bannedWords = [];
  35.         $routes = Route::getRoutes();
  36.  
  37.         foreach ($routes as $route) {
  38.             $uri = $route->uri();
  39.             if (!in_array($uri, $bannedWords)) {
  40.                 $bannedWords[] = $uri;
  41.             }
  42.         }
  43.  
  44.         return $bannedWords;
  45.     }
  46.  
  47.     private function isBannedWord($shortUrl)
  48.     {
  49.         return in_array($shortUrl, $this->bannedWords);
  50.     }
  51.     public function decode($hash)
  52.     {
  53.         $prefix = substr($hash, 0, 2);
  54.         $suffix = substr($hash, -2);
  55.         $hash = substr($hash, 2, -2);
  56.         $decoded = $this->hashids->decode($hash);
  57.         if (!empty($decoded)) {
  58.             $urlId = $decoded[0];
  59.             // Verify the prefix and suffix by calculating them again
  60.             if ($prefix === substr(md5($urlId), 0, 2) && $suffix === substr(sha1($urlId), -2)) {
  61.                 return $urlId;
  62.             }
  63.         }
  64.         return null;
  65.     }
  66. }
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement