<?php
/**
* Deserializes JSON API responses with a timeout.
*
* @param string $jsonString The JSON string to deserialize.
* @param int $timeout The timeout in seconds.
* @return mixed|null The deserialized object or null on failure.
* @throws Exception If deserialization fails.
*/
function deserializeWithTimeout(string $jsonString, int $timeout): mixed
{
$timedOut = false;
$result = null;
$context = stream_context_create([
'http' => [
'timeout' => $timeout,
],
]);
try {
$result = json_decode($jsonString, true, 512, JSON_THROW_ON_ERROR); // Use JSON_THROW_ON_ERROR for exceptions
} catch (JsonException $e) {
// Handle JSON decoding errors. Log or re-throw as needed.
error_log("JSON decoding error: " . $e->getMessage());
throw new Exception("Failed to deserialize JSON: " . $e->getMessage());
}
return $result;
}
// Example Usage (for testing)
/*
$json = '{
"name": "Test",
"value": 123
}';
try {
$data = deserializeWithTimeout($json, 2); // 2-second timeout
print_r($data);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
//Simulate a timeout scenario.
$longJson = str_repeat("a", 1000000); //Create a very long string
try{
$data = deserializeWithTimeout($longJson, 1);
print_r($data);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
*/
?>
Add your comment