1. <?php
  2. class ExecutionTracker {
  3. private $executionLogs = [];
  4. /**
  5. * Executes a text block and logs its execution.
  6. *
  7. * @param string $code The code to execute.
  8. * @param string $blockName A descriptive name for the code block.
  9. * @return mixed The result of the code execution, or null on error.
  10. */
  11. public function trackExecution(string $code, string $blockName) {
  12. $startTime = microtime(true); // Record start time
  13. ob_start(); // Start output buffering
  14. try {
  15. $result = eval($code); // Execute the code
  16. $executionTime = microtime(true) - $startTime; // Record end time
  17. $executionLogs[] = [
  18. 'blockName' => $blockName,
  19. 'startTime' => $startTime,
  20. 'endTime' => $executionTime,
  21. 'executionTime' => $executionTime - $startTime,
  22. 'result' => $result,
  23. ];
  24. return $result;
  25. } catch (Exception $e) {
  26. $executionTime = microtime(true) - $startTime;
  27. $executionLogs[] = [
  28. 'blockName' => $blockName,
  29. 'startTime' => $startTime,
  30. 'endTime' => $executionTime,
  31. 'executionTime' => $executionTime - $startTime,
  32. 'error' => $e->getMessage(),
  33. ];
  34. return null; // Indicate an error
  35. }
  36. }
  37. /**
  38. * Gets all execution logs.
  39. *
  40. * @return array The execution logs.
  41. */
  42. public function getLogs(): array {
  43. return $this->executionLogs;
  44. }
  45. /**
  46. * Clears all logs.
  47. */
  48. public function clearLogs(): void {
  49. $this->executionLogs = [];
  50. }
  51. }
  52. // Example Usage:
  53. $tracker = new ExecutionTracker();
  54. $tracker->trackExecution("echo 'Hello from block 1';", "Block 1");
  55. $tracker->trackExecution("var $x = 10; echo $x * 2;", "Block 2");
  56. $tracker->trackExecution("echo 'This will cause an error';", "Block 3");
  57. $logs = $tracker->getLogs();
  58. foreach ($logs as $log) {
  59. echo "Block: " . $log['blockName'] . "\n";
  60. echo "Start Time: " . date("Y-m-d H:i:s") . "\n";
  61. echo "End Time: " . date("Y-m-d H:i:s") . "\n";
  62. echo "Execution Time: " . number_format($log['executionTime'], 5) . " seconds\n";
  63. if (isset($log['result'])) {
  64. echo "Result: " . var_export($log['result'], true) . "\n";
  65. }
  66. if (isset($log['error'])) {
  67. echo "Error: " . $log['error'] . "\n";
  68. }
  69. echo "--------------------\n";
  70. }
  71. ?>

Add your comment