1. <?php
  2. /**
  3. * Releases resources of JSON responses for debugging with dry-run mode.
  4. *
  5. * @param mixed $data The data to be released. Can be a JSON string, object, or array.
  6. * @param bool $dryRun Whether to only simulate resource release (default: true).
  7. * @return void
  8. */
  9. function releaseJsonResources(mixed $data, bool $dryRun = true): void
  10. {
  11. if ($dryRun) {
  12. echo "Dry-run: Simulating resource release for data: " . (is_string($data) ? substr($data, 0, 50) . "..." : json_encode($data, JSON_PRETTY_PRINT));
  13. return;
  14. }
  15. if (is_string($data)) {
  16. // Decode the JSON string
  17. $decodedData = json_decode($data, true);
  18. if ($decodedData === null && json_last_error() !== JSON_ERROR_NONE) {
  19. echo "Error decoding JSON: " . json_last_error_msg() . PHP_EOL;
  20. return;
  21. }
  22. // Free memory used by the decoded data
  23. if (is_object($decodedData) || is_array($decodedData)) {
  24. unset($decodedData);
  25. $decodedData = null;
  26. }
  27. } elseif (is_object($data)) {
  28. // Free memory used by the object
  29. unset($data);
  30. $data = null;
  31. } elseif (is_array($data)) {
  32. // Free memory used by the array
  33. unset($data);
  34. $data = null;
  35. }
  36. }
  37. // Example usage (dry-run)
  38. releaseJsonResources('{"name": "John Doe", "age": 30}');
  39. // Example usage (actual release)
  40. $jsonString = '{"name": "Jane Doe", "age": 25}';
  41. releaseJsonResources($jsonString);
  42. //Example with an object
  43. class MyClass {}
  44. $myObject = new MyClass();
  45. releaseJsonResources($myObject);
  46. //Example with an array
  47. $myArray = [1,2,3];
  48. releaseJsonResources($myArray);
  49. ?>

Add your comment