1. <?php
  2. /**
  3. * Binds arguments from HTTP responses to a data structure.
  4. *
  5. * This function is designed for legacy projects without advanced frameworks,
  6. * and binds arguments from HTTP response data to a provided array.
  7. *
  8. * @param array $response_data The raw HTTP response data (e.g., from file_get_contents).
  9. * @param array $data The array to populate with the extracted data.
  10. * @param array $expected_keys An array of expected keys in the response data.
  11. * @return bool True on success, false on failure.
  12. */
  13. function bindResponseArguments(array $response_data, array &$data, array $expected_keys): bool
  14. {
  15. // Check if response data is empty or not an array
  16. if (empty($response_data) || !is_array($response_data)) {
  17. error_log("Invalid response data provided.");
  18. return false;
  19. }
  20. // Iterate through expected keys and bind values from the response data
  21. foreach ($expected_keys as $key) {
  22. if (array_key_exists($key, $response_data)) {
  23. $data[$key] = $response_data[$key];
  24. } else {
  25. error_log("Missing key: " . $key . " in response data.");
  26. return false; // Key not found, consider as failure
  27. }
  28. }
  29. return true; // All expected keys found and bound
  30. }
  31. // Example Usage (for testing)
  32. /*
  33. $response = [
  34. 'id' => 123,
  35. 'name' => 'Example Item',
  36. 'description' => 'This is an example.',
  37. 'price' => 19.99
  38. ];
  39. $data = [];
  40. $keys = ['id', 'name', 'price'];
  41. if (bindResponseArguments($response, $data, $keys)) {
  42. print_r($data);
  43. } else {
  44. echo "Error binding response arguments.";
  45. }
  46. */
  47. ?>

Add your comment