Skip to content

Commit

Permalink
Stop stopwatch events in case of exception
Browse files Browse the repository at this point in the history
  • Loading branch information
MatTheCat authored and fabpot committed Mar 17, 2023
1 parent 57b312f commit 1df20e4
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
10 changes: 6 additions & 4 deletions Debug/WrappedListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,12 @@ public function __invoke(object $event, string $eventName, EventDispatcherInterf

$e = $this->stopwatch->start($this->name, 'event_listener');

($this->optimizedListener ?? $this->listener)($event, $eventName, $dispatcher);

if ($e->isStarted()) {
$e->stop();
try {
($this->optimizedListener ?? $this->listener)($event, $eventName, $dispatcher);
} finally {
if ($e->isStarted()) {
$e->stop();
}
}

if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
Expand Down
20 changes: 20 additions & 0 deletions Tests/Debug/WrappedListenerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Component\EventDispatcher\Debug\WrappedListener;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Component\Stopwatch\StopwatchEvent;

class WrappedListenerTest extends TestCase
{
Expand Down Expand Up @@ -42,6 +43,25 @@ public static function provideListenersToDescribe()
[\Closure::fromCallable(function () {}), 'closure'],
];
}

public function testStopwatchEventIsStoppedWhenListenerThrows()
{
$stopwatchEvent = $this->createMock(StopwatchEvent::class);
$stopwatchEvent->expects(self::once())->method('isStarted')->willReturn(true);
$stopwatchEvent->expects(self::once())->method('stop');

$stopwatch = $this->createStub(Stopwatch::class);
$stopwatch->method('start')->willReturn($stopwatchEvent);

$dispatcher = $this->createStub(EventDispatcherInterface::class);

$wrappedListener = new WrappedListener(function () { throw new \Exception(); }, null, $stopwatch, $dispatcher);

try {
$wrappedListener(new \stdClass(), 'foo', $dispatcher);
} catch (\Exception $ex) {
}
}
}

class FooListener
Expand Down

0 comments on commit 1df20e4

Please sign in to comment.