1. <?php
  2. /**
  3. * Deserializes JSON API responses with a timeout.
  4. *
  5. * @param string $jsonString The JSON string to deserialize.
  6. * @param int $timeout The timeout in seconds.
  7. * @return mixed|null The deserialized object or null on failure.
  8. * @throws Exception If deserialization fails.
  9. */
  10. function deserializeWithTimeout(string $jsonString, int $timeout): mixed
  11. {
  12. $timedOut = false;
  13. $result = null;
  14. $context = stream_context_create([
  15. 'http' => [
  16. 'timeout' => $timeout,
  17. ],
  18. ]);
  19. try {
  20. $result = json_decode($jsonString, true, 512, JSON_THROW_ON_ERROR); // Use JSON_THROW_ON_ERROR for exceptions
  21. } catch (JsonException $e) {
  22. // Handle JSON decoding errors. Log or re-throw as needed.
  23. error_log("JSON decoding error: " . $e->getMessage());
  24. throw new Exception("Failed to deserialize JSON: " . $e->getMessage());
  25. }
  26. return $result;
  27. }
  28. // Example Usage (for testing)
  29. /*
  30. $json = '{
  31. "name": "Test",
  32. "value": 123
  33. }';
  34. try {
  35. $data = deserializeWithTimeout($json, 2); // 2-second timeout
  36. print_r($data);
  37. } catch (Exception $e) {
  38. echo "Error: " . $e->getMessage() . "\n";
  39. }
  40. //Simulate a timeout scenario.
  41. $longJson = str_repeat("a", 1000000); //Create a very long string
  42. try{
  43. $data = deserializeWithTimeout($longJson, 1);
  44. print_r($data);
  45. } catch (Exception $e) {
  46. echo "Error: " . $e->getMessage() . "\n";
  47. }
  48. */
  49. ?>

Add your comment