<?php
class ExecutionTracker {
private $executionLogs = [];
/**
* Executes a text block and logs its execution.
*
* @param string $code The code to execute.
* @param string $blockName A descriptive name for the code block.
* @return mixed The result of the code execution, or null on error.
*/
public function trackExecution(string $code, string $blockName) {
$startTime = microtime(true); // Record start time
ob_start(); // Start output buffering
try {
$result = eval($code); // Execute the code
$executionTime = microtime(true) - $startTime; // Record end time
$executionLogs[] = [
'blockName' => $blockName,
'startTime' => $startTime,
'endTime' => $executionTime,
'executionTime' => $executionTime - $startTime,
'result' => $result,
];
return $result;
} catch (Exception $e) {
$executionTime = microtime(true) - $startTime;
$executionLogs[] = [
'blockName' => $blockName,
'startTime' => $startTime,
'endTime' => $executionTime,
'executionTime' => $executionTime - $startTime,
'error' => $e->getMessage(),
];
return null; // Indicate an error
}
}
/**
* Gets all execution logs.
*
* @return array The execution logs.
*/
public function getLogs(): array {
return $this->executionLogs;
}
/**
* Clears all logs.
*/
public function clearLogs(): void {
$this->executionLogs = [];
}
}
// Example Usage:
$tracker = new ExecutionTracker();
$tracker->trackExecution("echo 'Hello from block 1';", "Block 1");
$tracker->trackExecution("var $x = 10; echo $x * 2;", "Block 2");
$tracker->trackExecution("echo 'This will cause an error';", "Block 3");
$logs = $tracker->getLogs();
foreach ($logs as $log) {
echo "Block: " . $log['blockName'] . "\n";
echo "Start Time: " . date("Y-m-d H:i:s") . "\n";
echo "End Time: " . date("Y-m-d H:i:s") . "\n";
echo "Execution Time: " . number_format($log['executionTime'], 5) . " seconds\n";
if (isset($log['result'])) {
echo "Result: " . var_export($log['result'], true) . "\n";
}
if (isset($log['error'])) {
echo "Error: " . $log['error'] . "\n";
}
echo "--------------------\n";
}
?>
Add your comment