Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion formwork/src/Debug/Debug.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand All @@ -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;
Expand Down Expand Up @@ -224,16 +236,30 @@ 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();
}
if (!self::$stylesDumped) {
echo '<style>' . self::$css . '</style>', '<script>' . self::$js . '</script>';
self::$stylesDumped = true;
}
echo '<pre class="__formwork-dump">';
if ($info = self::getContext()) {
echo sprintf(
'<div class="__formwork-dump-item"><span class="__type-name" title="%s">%s</span>, line <span class="__type-number">%d</span></div>',
$info['file'],
basename($info['file']),
$info['line']
);
}
foreach ($data as $d) {
echo self::dumpToString($d);
echo sprintf('<div class="__formwork-dump-item">%s</div>', self::outputData($d));
}
echo '</pre>';
echo '<script>__formwork_dump_goto(window.location.hash.slice(1))</script>';
}

Expand Down Expand Up @@ -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;
}
}