1. <?php
  2. /**
  3. * Buffers JSON responses for internal tooling, supporting older PHP versions.
  4. *
  5. * @param mixed $data The data to buffer (should be JSON-serializable).
  6. * @param callable $callback A callback function to execute when the buffer is full.
  7. * The callback receives the buffered data as an argument.
  8. * @param int $buffer_size The maximum size of the buffer in bytes. Defaults to 10240 (10KB).
  9. * @return string The buffered JSON data.
  10. */
  11. function bufferJson(mixed $data, callable $callback, int $buffer_size = 10240): string
  12. {
  13. $buffer = '';
  14. $callback_called = false;
  15. while (true) {
  16. $json_string = json_encode($data); // Serialize to JSON
  17. if ($json_string === false) {
  18. // Handle JSON encoding errors. Important for robust handling.
  19. if(!$callback_called){
  20. $callback($data); // Pass the original data if encoding fails
  21. }
  22. return $buffer;
  23. }
  24. $buffer .= $json_string; // Append to the buffer
  25. $data = null; // Clear the data after processing
  26. if (strlen($buffer) >= $buffer_size) {
  27. if (!$callback_called) {
  28. $callback($buffer); // Call the callback when the buffer is full
  29. $callback_called = true;
  30. }
  31. $buffer = ''; // Reset the buffer
  32. }
  33. // Check for end of input (optional, depending on your input source)
  34. // For example, if reading from a stream, you might check for stream_end()
  35. usleep(1000); // Add a small delay to avoid busy-waiting
  36. }
  37. }
  38. //Example Usage
  39. /*
  40. $my_data = ['name' => 'John Doe', 'age' => 30];
  41. $my_callback = function ($data) {
  42. echo "Buffered JSON Data:\n" . $data . "\n";
  43. };
  44. $buffered_json = bufferJson($my_data, $my_callback, 5120); //buffer size 5KB
  45. echo "Total buffered data size: " . strlen($buffered_json) . " bytes\n";
  46. */
  47. ?>

Add your comment