diff --git a/formwork/src/Debug/Debug.php b/formwork/src/Debug/Debug.php index b40591055..5ee8da242 100644 --- a/formwork/src/Debug/Debug.php +++ b/formwork/src/Debug/Debug.php @@ -18,6 +18,12 @@ final class Debug */ private const int INDENT_SPACES = 2; + /** + * Maximum number of stack frames to include in the backtrace to get context + * (adjust according to the maximum nesting depth of the call to `getContext()`) + */ + private const int BACKTRACE_LIMIT = 3; + /** * CSS styles for debug output */ @@ -35,6 +41,12 @@ final class Debug overflow-x: auto; } + .__formwork-dump-item + .__formwork-dump-item { + border-top: 1px dashed #ccc; + margin-top: 8px; + padding-top: 8px; + } + .color-scheme-dark .__formwork-dump { background-color: #333; color: #f0f0f0; @@ -224,6 +236,10 @@ function __formwork_dump_goto(target) { */ public static function dump(mixed ...$data): void { + // Dump data only if the client explicitly accepts HTML + if (!str_contains($_SERVER['HTTP_ACCEPT'] ?? '*/*', 'text/html')) { + return; + } if (!headers_sent()) { ob_start(); } @@ -231,9 +247,19 @@ public static function dump(mixed ...$data): void echo '', ''; self::$stylesDumped = true; } + echo '
';
+        if ($info = self::getContext()) {
+            echo sprintf(
+                '
%s, line %d
', + $info['file'], + basename($info['file']), + $info['line'] + ); + } foreach ($data as $d) { - echo self::dumpToString($d); + echo sprintf('
%s
', self::outputData($d)); } + echo '
'; echo ''; } @@ -422,4 +448,18 @@ private static function outputData(mixed $data, int $indent = 0): string throw new UnexpectedValueException('Unexpected value for debug'); } + + /** + * @return ?array{file: string, line: int} + */ + private static function getContext(): ?array + { + $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, self::BACKTRACE_LIMIT); + foreach ($backtrace as $frame) { + if (isset($frame['file'], $frame['line']) && $frame['file'] !== __FILE__) { + return ['file' => $frame['file'], 'line' => $frame['line']]; + } + } + return null; + } }