<?php
/**
* Buffers JSON responses for internal tooling, supporting older PHP versions.
*
* @param mixed $data The data to buffer (should be JSON-serializable).
* @param callable $callback A callback function to execute when the buffer is full.
* The callback receives the buffered data as an argument.
* @param int $buffer_size The maximum size of the buffer in bytes. Defaults to 10240 (10KB).
* @return string The buffered JSON data.
*/
function bufferJson(mixed $data, callable $callback, int $buffer_size = 10240): string
{
$buffer = '';
$callback_called = false;
while (true) {
$json_string = json_encode($data); // Serialize to JSON
if ($json_string === false) {
// Handle JSON encoding errors. Important for robust handling.
if(!$callback_called){
$callback($data); // Pass the original data if encoding fails
}
return $buffer;
}
$buffer .= $json_string; // Append to the buffer
$data = null; // Clear the data after processing
if (strlen($buffer) >= $buffer_size) {
if (!$callback_called) {
$callback($buffer); // Call the callback when the buffer is full
$callback_called = true;
}
$buffer = ''; // Reset the buffer
}
// Check for end of input (optional, depending on your input source)
// For example, if reading from a stream, you might check for stream_end()
usleep(1000); // Add a small delay to avoid busy-waiting
}
}
//Example Usage
/*
$my_data = ['name' => 'John Doe', 'age' => 30];
$my_callback = function ($data) {
echo "Buffered JSON Data:\n" . $data . "\n";
};
$buffered_json = bufferJson($my_data, $my_callback, 5120); //buffer size 5KB
echo "Total buffered data size: " . strlen($buffered_json) . " bytes\n";
*/
?>
Add your comment