<?php
/**
* Hashes API response values for hypothesis validation with limited memory.
*
* @param array $data The API response data.
* @param string $hash_algorithm The hashing algorithm to use (e.g., 'sha256', 'md5').
* @param int $chunk_size The size of data chunks to process (adjust for memory limits).
* @return array An associative array where keys are data element indices and values are their hashes, or an empty array on error.
*/
function hash_api_data(array $data, string $hash_algorithm = 'sha256', int $chunk_size = 4096): array
{
$hashes = [];
$hash = null;
// Initialize the hash object based on the specified algorithm.
switch (strtolower($hash_algorithm)) {
case 'sha256':
$hash = hash_init('sha256');
break;
case 'md5':
$hash = hash_init('md5');
break;
default:
return []; // Invalid algorithm
}
// Iterate over the data in chunks to manage memory.
for ($i = 0; $i < count($data); $i += $chunk_size) {
$chunk = array_slice($data, $i, $chunk_size);
// Hash the chunk.
if ($hash !== null) {
hash_update($hash, implode('', $chunk));
}
// Reset the hash if it's a new chunk.
if ($i > 0) {
$hashes[$i - 1] = bin2hex(hash_digest($hash, '')); // Store the hash
hash_reset($hash);
}
}
// Hash the remaining data (if any).
if ($hash !== null) {
$hashes[$i] = bin2hex(hash_digest($hash, ''));
}
return $hashes;
}
/**
* Example usage
*/
// Sample API response data
//$api_response = ['id' => 123, 'name' => 'Example', 'value' => 42, 'description' => 'This is a test'];
// Hash the data using SHA-256
//$hashes = hash_api_data($api_response, 'sha256');
// Print the hashes
//print_r($hashes);
?>
Add your comment