Skip to content
Open
Show file tree
Hide file tree
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
16 changes: 14 additions & 2 deletions packages/debug/src/Debug.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,10 @@ public static function resolve(): self
*/
public function log(array $items, bool $writeToLog = true, bool $writeToOut = true): void
{
static $isDispatchingItemsDebuggedEvent = false;

$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$callPath = $trace[1]['file'] . ':' . $trace[1]['line'];
$callPath = ($trace[1]['file'] ?? 'unknown') . ':' . ($trace[1]['line'] ?? 0);

if ($writeToLog) {
$this->writeToLog($items, $callPath);
Expand All @@ -51,7 +53,17 @@ public function log(array $items, bool $writeToLog = true, bool $writeToOut = tr
$this->writeToOut($items, $callPath);
}

$this->eventBus?->dispatch(new ItemsDebugged($items));
if (! $this->eventBus || $isDispatchingItemsDebuggedEvent) {
return;
}

$isDispatchingItemsDebuggedEvent = true;

try {
$this->eventBus->dispatch(new ItemsDebugged($items));
} finally {
$isDispatchingItemsDebuggedEvent = false;
}
}

private function writeToLog(array $items, string $callPath): void
Expand Down
18 changes: 18 additions & 0 deletions tests/Integration/Debug/DebugTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Tests\Tempest\Integration\Debug;

use PHPUnit\Framework\Attributes\Test;
use stdClass;
use Tempest\Debug\Debug;
use Tempest\Debug\ItemsDebugged;
Expand All @@ -26,4 +27,21 @@ public function test_event(): void

Debug::resolve()->log(['foo', $class], writeToLog: false, writeToOut: false);
}

#[Test]
public function recursive_debug_inside_event_listener_does_not_cause_infinite_loop(): void
{
$dispatchCount = 0;

$eventBus = $this->container->get(EventBus::class);
$eventBus->listen(function (ItemsDebugged $event) use (&$dispatchCount): void {
$dispatchCount++;

Debug::resolve()->log(['recursive call'], writeToLog: false, writeToOut: false);
});

Debug::resolve()->log(['initial call'], writeToLog: false, writeToOut: false);

$this->assertSame(1, $dispatchCount);
}
}