From a327f5c167da6a43bba756f821dee0f9a7cad82e Mon Sep 17 00:00:00 2001 From: Daniel Supernault Date: Sat, 18 Jul 2020 17:53:40 -0600 Subject: [PATCH] Add HashidService --- app/Services/HashidService.php | 50 ++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 app/Services/HashidService.php diff --git a/app/Services/HashidService.php b/app/Services/HashidService.php new file mode 100644 index 00000000..d23c5c52 --- /dev/null +++ b/app/Services/HashidService.php @@ -0,0 +1,50 @@ + PHP_INT_MAX || strlen($id) < self::MIN_LIMIT) { + return null; + } + $key = "hashids:{$id}"; + return Cache::remember($key, now()->hours(48), function() use($id) { + $cmap = self::CMAP; + $base = strlen($cmap); + $shortcode = ''; + while($id) { + $id = ($id - ($r = $id % $base)) / $base; + $shortcode = $cmap{$r} . $shortcode; + }; + return $shortcode; + }); + } + + public static function decode($short) + { + $len = strlen($short); + if($len < 3 || $len > 11) { + return null; + } + $id = 0; + foreach(str_split($short) as $needle) { + $pos = strpos(self::CMAP, $needle); + // if(!$pos) { + // return null; + // } + $id = ($id*64) + $pos; + } + if(strlen($id) < self::MIN_LIMIT) { + return null; + } + return $id; + } + +} \ No newline at end of file