<?php
/**
* Releases resources of JSON responses for debugging with dry-run mode.
*
* @param mixed $data The data to be released. Can be a JSON string, object, or array.
* @param bool $dryRun Whether to only simulate resource release (default: true).
* @return void
*/
function releaseJsonResources(mixed $data, bool $dryRun = true): void
{
if ($dryRun) {
echo "Dry-run: Simulating resource release for data: " . (is_string($data) ? substr($data, 0, 50) . "..." : json_encode($data, JSON_PRETTY_PRINT));
return;
}
if (is_string($data)) {
// Decode the JSON string
$decodedData = json_decode($data, true);
if ($decodedData === null && json_last_error() !== JSON_ERROR_NONE) {
echo "Error decoding JSON: " . json_last_error_msg() . PHP_EOL;
return;
}
// Free memory used by the decoded data
if (is_object($decodedData) || is_array($decodedData)) {
unset($decodedData);
$decodedData = null;
}
} elseif (is_object($data)) {
// Free memory used by the object
unset($data);
$data = null;
} elseif (is_array($data)) {
// Free memory used by the array
unset($data);
$data = null;
}
}
// Example usage (dry-run)
releaseJsonResources('{"name": "John Doe", "age": 30}');
// Example usage (actual release)
$jsonString = '{"name": "Jane Doe", "age": 25}';
releaseJsonResources($jsonString);
//Example with an object
class MyClass {}
$myObject = new MyClass();
releaseJsonResources($myObject);
//Example with an array
$myArray = [1,2,3];
releaseJsonResources($myArray);
?>
Add your comment