HashidService.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace App\Services;
  3. use Cache;
  4. class HashidService {
  5. public const MIN_LIMIT = 15;
  6. public const CMAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
  7. public static function encode($id, $minLimit = true)
  8. {
  9. if(!is_numeric($id) || $id > PHP_INT_MAX) {
  10. return null;
  11. }
  12. if($minLimit && strlen($id) < self::MIN_LIMIT) {
  13. return null;
  14. }
  15. $key = "hashids:{$id}";
  16. return Cache::remember($key, now()->hours(48), function() use($id) {
  17. $cmap = self::CMAP;
  18. $base = strlen($cmap);
  19. $shortcode = '';
  20. while($id) {
  21. $id = ($id - ($r = $id % $base)) / $base;
  22. $shortcode = $cmap[$r] . $shortcode;
  23. }
  24. return $shortcode;
  25. });
  26. }
  27. public static function decode($short)
  28. {
  29. $len = strlen($short);
  30. if($len < 3 || $len > 11) {
  31. return null;
  32. }
  33. $id = 0;
  34. foreach(str_split($short) as $needle) {
  35. $pos = strpos(self::CMAP, $needle);
  36. // if(!$pos) {
  37. // return null;
  38. // }
  39. $id = ($id*64) + $pos;
  40. }
  41. if(strlen($id) < self::MIN_LIMIT) {
  42. return null;
  43. }
  44. return $id;
  45. }
  46. }