HashidService.php 995 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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)
  8. {
  9. if(!is_numeric($id) || $id > PHP_INT_MAX || strlen($id) < self::MIN_LIMIT) {
  10. return null;
  11. }
  12. $key = "hashids:{$id}";
  13. return Cache::remember($key, now()->hours(48), function() use($id) {
  14. $cmap = self::CMAP;
  15. $base = strlen($cmap);
  16. $shortcode = '';
  17. while($id) {
  18. $id = ($id - ($r = $id % $base)) / $base;
  19. $shortcode = $cmap[$r] . $shortcode;
  20. };
  21. return $shortcode;
  22. });
  23. }
  24. public static function decode($short)
  25. {
  26. $len = strlen($short);
  27. if($len < 3 || $len > 11) {
  28. return null;
  29. }
  30. $id = 0;
  31. foreach(str_split($short) as $needle) {
  32. $pos = strpos(self::CMAP, $needle);
  33. // if(!$pos) {
  34. // return null;
  35. // }
  36. $id = ($id*64) + $pos;
  37. }
  38. if(strlen($id) < self::MIN_LIMIT) {
  39. return null;
  40. }
  41. return $id;
  42. }
  43. }