From b7840c28a6a5a05fffab7a74ee29d9d4b2b493ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alvaro=20C=C3=A1nepa?= Date: Fri, 7 Feb 2025 13:09:49 -0300 Subject: [PATCH] Add hex support Check for non numeric `getKey()` model response and use hex encode/decode methods --- src/HasHashid.php | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/src/HasHashid.php b/src/HasHashid.php index 80e9bb7..8622d91 100644 --- a/src/HasHashid.php +++ b/src/HasHashid.php @@ -32,8 +32,9 @@ public function hashid() */ public function hashidToId($hashid) { - return @Hashids::connection($this->getHashidsConnection()) - ->decode($hashid)[0]; + $obConnection = $this->connection(); + + return $this->useHex() ? $obConnection->decodeHex($hashid) : $obConnection->decode($hashid)[0]; } /** @@ -44,8 +45,9 @@ public function hashidToId($hashid) */ public function idToHashid($id) { - return @Hashids::connection($this->getHashidsConnection()) - ->encode($id); + $obConnection = $this->connection(); + + return $this->useHex() ? $obConnection->encodeHex($id) : $obConnection->encode($id); } public function getHashidsConnection() @@ -54,7 +56,23 @@ public function getHashidsConnection() } protected function getHashidAttribute() - { - return $this->hashid(); - } + { + return $this->hashid(); + } + + /** + * @return bool + */ + public function useHex(): bool + { + return !is_numeric($this->getKey()); + } + + /** + * @return MainHashids + */ + protected function connection(): MainHashids + { + return @Hashids::connection($this->getHashidsConnection()); + } }