Skip to content

Commit 1df20e4

Browse files
MatTheCatfabpot
authored andcommitted
Stop stopwatch events in case of exception
1 parent 57b312f commit 1df20e4

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

Debug/WrappedListener.php

+6-4
Original file line numberDiff line numberDiff line change
@@ -114,10 +114,12 @@ public function __invoke(object $event, string $eventName, EventDispatcherInterf
114114

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

117-
($this->optimizedListener ?? $this->listener)($event, $eventName, $dispatcher);
118-
119-
if ($e->isStarted()) {
120-
$e->stop();
117+
try {
118+
($this->optimizedListener ?? $this->listener)($event, $eventName, $dispatcher);
119+
} finally {
120+
if ($e->isStarted()) {
121+
$e->stop();
122+
}
121123
}
122124

123125
if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) {

Tests/Debug/WrappedListenerTest.php

+20
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
use Symfony\Component\EventDispatcher\Debug\WrappedListener;
1616
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
1717
use Symfony\Component\Stopwatch\Stopwatch;
18+
use Symfony\Component\Stopwatch\StopwatchEvent;
1819

1920
class WrappedListenerTest extends TestCase
2021
{
@@ -42,6 +43,25 @@ public static function provideListenersToDescribe()
4243
[\Closure::fromCallable(function () {}), 'closure'],
4344
];
4445
}
46+
47+
public function testStopwatchEventIsStoppedWhenListenerThrows()
48+
{
49+
$stopwatchEvent = $this->createMock(StopwatchEvent::class);
50+
$stopwatchEvent->expects(self::once())->method('isStarted')->willReturn(true);
51+
$stopwatchEvent->expects(self::once())->method('stop');
52+
53+
$stopwatch = $this->createStub(Stopwatch::class);
54+
$stopwatch->method('start')->willReturn($stopwatchEvent);
55+
56+
$dispatcher = $this->createStub(EventDispatcherInterface::class);
57+
58+
$wrappedListener = new WrappedListener(function () { throw new \Exception(); }, null, $stopwatch, $dispatcher);
59+
60+
try {
61+
$wrappedListener(new \stdClass(), 'foo', $dispatcher);
62+
} catch (\Exception $ex) {
63+
}
64+
}
4565
}
4666

4767
class FooListener

0 commit comments

Comments
 (0)