Skip to content

Commit 5dfec10

Browse files
committed
Support for nested commands
1 parent 70432f2 commit 5dfec10

File tree

1 file changed

+31
-7
lines changed

1 file changed

+31
-7
lines changed

src/Symfony/Component/Console/EventSubscriber.php

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,26 @@
33

44
namespace PcComponentes\ElasticAPM\Symfony\Component\Console;
55

6+
use Symfony\Component\Console\Command\Command;
67
use Symfony\Component\Console\ConsoleEvents;
78
use Symfony\Component\Console\Event\ConsoleCommandEvent;
89
use Symfony\Component\Console\Event\ConsoleErrorEvent;
910
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
1011
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
1112
use ZoiloMora\ElasticAPM\ElasticApmTracer;
12-
use ZoiloMora\ElasticAPM\Events\Transaction\Transaction;
1313

1414
final class EventSubscriber implements EventSubscriberInterface
1515
{
1616
private ElasticApmTracer $elasticApmTracer;
1717

18-
private Transaction $transaction;
18+
private array $transactions;
19+
private array $spans;
1920

2021
public function __construct(ElasticApmTracer $elasticApmTracer)
2122
{
2223
$this->elasticApmTracer = $elasticApmTracer;
24+
$this->transactions = [];
25+
$this->spans = [];
2326
}
2427

2528
public static function getSubscribedEvents(): array
@@ -34,19 +37,39 @@ public static function getSubscribedEvents(): array
3437
public function onConsoleCommandEvent(ConsoleCommandEvent $event): void
3538
{
3639
$command = $event->getCommand();
40+
$key = $this->transactionKey($command);
3741

38-
$this->transaction = $this->elasticApmTracer->startTransaction(
42+
if (0 !== \count($this->transactions)) {
43+
$this->spans[$key] = $this->elasticApmTracer->startSpan(
44+
$command->getName(),
45+
'console',
46+
);
47+
}
48+
49+
$this->transactions[$key] = $this->elasticApmTracer->startTransaction(
3950
$command->getName(),
4051
'console',
4152
);
4253
}
4354

4455
public function onConsoleTerminateEvent(ConsoleTerminateEvent $event): void
4556
{
46-
$this->transaction->stop(
57+
$key = $this->transactionKey(
58+
$event->getCommand(),
59+
);
60+
61+
$this->transactions[$key]->stop(
4762
(string) $event->getExitCode(),
4863
);
4964

65+
if (true === \array_key_exists($key, $this->spans)) {
66+
$this->spans[$key]->stop();
67+
}
68+
69+
if (\array_key_first($this->transactions) !== $key) {
70+
return;
71+
}
72+
5073
$this->elasticApmTracer->flush();
5174
}
5275

@@ -55,9 +78,10 @@ public function onConsoleErrorEvent(ConsoleErrorEvent $event): void
5578
$this->elasticApmTracer->captureException(
5679
$event->getError(),
5780
);
81+
}
5882

59-
$this->transaction->stop(
60-
(string) $event->getExitCode(),
61-
);
83+
private function transactionKey(Command $command): int
84+
{
85+
return \spl_object_id($command);
6286
}
6387
}

0 commit comments

Comments
 (0)