Passed
Push — master ( 79a79c...9c574d )
by Thomas Mauro
02:27
created

handleForManager()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 11
c 1
b 0
f 0
nc 5
nop 3
dl 0
loc 18
rs 9.9
1
<?php
2
3
declare(strict_types=1);
4
5
namespace TMV\Laminas\Messenger\Bridge\Doctrine\Middleware;
6
7
use Doctrine\ORM\EntityManagerInterface;
8
use Doctrine\Persistence\ManagerRegistry;
9
use Psr\Log\LoggerInterface;
10
use Symfony\Component\Messenger\Envelope;
11
use Symfony\Component\Messenger\Middleware\StackInterface;
12
13
/**
14
 * @final
15
 */
16
class DoctrineOpenTransactionLoggerMiddleware extends AbstractDoctrineMiddleware
17
{
18
    private ?LoggerInterface $logger;
19
20
    private bool $isHandling = false;
21
22
    public function __construct(
23
        ManagerRegistry $managerRegistry,
24
        ?string $entityManagerName = null,
25
        ?LoggerInterface $logger = null,
26
    ) {
27
        parent::__construct($managerRegistry, $entityManagerName);
28
        $this->logger = $logger;
29
    }
30
31
    protected function handleForManager(EntityManagerInterface $entityManager, Envelope $envelope, StackInterface $stack): Envelope
32
    {
33
        if ($this->isHandling) {
34
            return $stack->next()->handle($envelope, $stack);
35
        }
36
37
        $this->isHandling = true;
38
        $initialTransactionLevel = $entityManager->getConnection()->getTransactionNestingLevel();
39
40
        try {
41
            return $stack->next()->handle($envelope, $stack);
42
        } finally {
43
            if ($this->logger && $entityManager->getConnection()->getTransactionNestingLevel() > $initialTransactionLevel) {
44
                $this->logger->error('A handler opened a transaction but did not close it.', [
45
                    'message' => $envelope->getMessage(),
46
                ]);
47
            }
48
            $this->isHandling = false;
49
        }
50
    }
51
}
52