<?php
/**
* Binds arguments from HTTP responses to a data structure.
*
* This function is designed for legacy projects without advanced frameworks,
* and binds arguments from HTTP response data to a provided array.
*
* @param array $response_data The raw HTTP response data (e.g., from file_get_contents).
* @param array $data The array to populate with the extracted data.
* @param array $expected_keys An array of expected keys in the response data.
* @return bool True on success, false on failure.
*/
function bindResponseArguments(array $response_data, array &$data, array $expected_keys): bool
{
// Check if response data is empty or not an array
if (empty($response_data) || !is_array($response_data)) {
error_log("Invalid response data provided.");
return false;
}
// Iterate through expected keys and bind values from the response data
foreach ($expected_keys as $key) {
if (array_key_exists($key, $response_data)) {
$data[$key] = $response_data[$key];
} else {
error_log("Missing key: " . $key . " in response data.");
return false; // Key not found, consider as failure
}
}
return true; // All expected keys found and bound
}
// Example Usage (for testing)
/*
$response = [
'id' => 123,
'name' => 'Example Item',
'description' => 'This is an example.',
'price' => 19.99
];
$data = [];
$keys = ['id', 'name', 'price'];
if (bindResponseArguments($response, $data, $keys)) {
print_r($data);
} else {
echo "Error binding response arguments.";
}
*/
?>
Add your comment