From a1c744b28d4bea9f5d4094ceb93ffc2f909084da Mon Sep 17 00:00:00 2001 From: mustapayev Date: Sun, 29 Dec 2024 12:32:44 +0100 Subject: [PATCH] refactor: hash AbstractCrypt for better modularity --- src/Crypt/AbstractCrypt.php | 42 +++++++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/src/Crypt/AbstractCrypt.php b/src/Crypt/AbstractCrypt.php index d62ac7d7..572dae9b 100644 --- a/src/Crypt/AbstractCrypt.php +++ b/src/Crypt/AbstractCrypt.php @@ -59,12 +59,7 @@ public function hashFromParams(string $storeKey, array $data, string $hashParams */ $hashParamsArr = \explode($paramSeparator, $hashParams); - $paramsVal = ''; - foreach ($hashParamsArr as $paramKey) { - $paramsVal .= $this->recursiveFind($data, $paramKey); - } - - $hashVal = $this->concatenateHashKey($storeKey, $paramsVal); + $hashVal = $this->buildHashString($data, $hashParamsArr, '', $storeKey); return $this->hashString($hashVal, $storeKey); } @@ -88,6 +83,41 @@ protected function concatenateHashKey(string $hashKey, string $hashString): stri return $hashString.$hashKey; } + /** + * @param array $data data from which the hash string will be built + * @param string[] $paramNames parameter names that will be used in hash calculation + * @param string $separator separator between the parameter values + * @param string|null $storeKey secret key of the API, will be attached to the hash string if provided + * + * @return string string data to be hashed + */ + protected function buildHashString(array $data, array $paramNames, string $separator = '', ?string $storeKey = null): string + { + $paramsVal = \implode($separator, $this->buildHashData($data, $paramNames)); + + if (null !== $storeKey) { + $paramsVal = $this->concatenateHashKey($storeKey, $paramsVal); + } + + return $paramsVal; + } + + /** + * @param array $data data from which the hash string will be built + * @param string[] $paramNames parameter names that will be used in hash calculation + * + * @return string[] + */ + protected function buildHashData(array $data, array $paramNames): array + { + $paramsVal = []; + foreach ($paramNames as $paramKey) { + $paramsVal[] = $this->recursiveFind($data, $paramKey); + } + + return $paramsVal; + } + /** * @param array $haystack (multidimensional) array * @param string $needle key name that will be searched in the (multidimensional) array