HashidService.php 852 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. <?php
  2. namespace App\Services;
  3. class HashidService
  4. {
  5. public const CMAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
  6. public static function encode($id, $minLimit = true)
  7. {
  8. if (! is_numeric($id) || $id > PHP_INT_MAX) {
  9. return null;
  10. }
  11. $cmap = self::CMAP;
  12. $base = strlen($cmap);
  13. $shortcode = '';
  14. while ($id) {
  15. $id = ($id - ($r = $id % $base)) / $base;
  16. $shortcode = $cmap[$r].$shortcode;
  17. }
  18. return $shortcode;
  19. }
  20. public static function decode($short = false)
  21. {
  22. if (! $short) {
  23. return;
  24. }
  25. $id = 0;
  26. foreach (str_split($short) as $needle) {
  27. $pos = strpos(self::CMAP, $needle);
  28. $id = ($id * 64) + $pos;
  29. }
  30. return $id;
  31. }
  32. }