Immutable hash for arrays, add not sort keys flag

This commit is contained in:
2026-09-18 21:53:36 +09:00
parent 3a33f07ae7
commit 369f2e2586
3 changed files with 42 additions and 7 deletions
+1
View File
@@ -113,6 +113,7 @@ $tests = [
];
foreach ($tests as $test) {
print "IMMUTABLE HASH FOR ARRAY: " . Hash::generateImmutableHashForArray($test) . "<br>";
print "IMMUTABLE HASH FOR ARRAY: " . Hash::generateImmutableHashForArray($test, sort_keys:false) . "<br>";
print "SERIALIZED HASH FOR ARRAY: " . hash(Hash::DEFAULT_HASH, serialize($test)) . "<br>";
}
+7 -2
View File
@@ -215,17 +215,22 @@ class Hash
/**
* generate a hash over any array data
* optional will not sort keys and so create hashes based on the original data.
* for correct array comapre it is recommended to keep sort keys on
*
* @param array<mixed> $data
* @param bool $sort_keys [true] Whether to sort the array keys before hashing
* @return string
*/
public static function generateImmutableHashForArray(array $data): string
public static function generateImmutableHashForArray(array $data, bool $sort_keys = true): string
{
// Create a sorted copy to ensure consistent hashing
// Generate hash using serialize for better accuracy
return hash(
self::DEFAULT_HASH,
serialize(ArrayHandler::createSortedArrayByKey($data))
serialize(
$sort_keys ? ArrayHandler::createSortedArrayByKey($data) : $data
)
);
}
}