1. <?php
  2. /**
  3. * Hashes API response values for hypothesis validation with limited memory.
  4. *
  5. * @param array $data The API response data.
  6. * @param string $hash_algorithm The hashing algorithm to use (e.g., 'sha256', 'md5').
  7. * @param int $chunk_size The size of data chunks to process (adjust for memory limits).
  8. * @return array An associative array where keys are data element indices and values are their hashes, or an empty array on error.
  9. */
  10. function hash_api_data(array $data, string $hash_algorithm = 'sha256', int $chunk_size = 4096): array
  11. {
  12. $hashes = [];
  13. $hash = null;
  14. // Initialize the hash object based on the specified algorithm.
  15. switch (strtolower($hash_algorithm)) {
  16. case 'sha256':
  17. $hash = hash_init('sha256');
  18. break;
  19. case 'md5':
  20. $hash = hash_init('md5');
  21. break;
  22. default:
  23. return []; // Invalid algorithm
  24. }
  25. // Iterate over the data in chunks to manage memory.
  26. for ($i = 0; $i < count($data); $i += $chunk_size) {
  27. $chunk = array_slice($data, $i, $chunk_size);
  28. // Hash the chunk.
  29. if ($hash !== null) {
  30. hash_update($hash, implode('', $chunk));
  31. }
  32. // Reset the hash if it's a new chunk.
  33. if ($i > 0) {
  34. $hashes[$i - 1] = bin2hex(hash_digest($hash, '')); // Store the hash
  35. hash_reset($hash);
  36. }
  37. }
  38. // Hash the remaining data (if any).
  39. if ($hash !== null) {
  40. $hashes[$i] = bin2hex(hash_digest($hash, ''));
  41. }
  42. return $hashes;
  43. }
  44. /**
  45. * Example usage
  46. */
  47. // Sample API response data
  48. //$api_response = ['id' => 123, 'name' => 'Example', 'value' => 42, 'description' => 'This is a test'];
  49. // Hash the data using SHA-256
  50. //$hashes = hash_api_data($api_response, 'sha256');
  51. // Print the hashes
  52. //print_r($hashes);
  53. ?>

Add your comment