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

DoctrinePingConnectionMiddleware   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 37
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A executeDummySql() 0 3 1
A pingConnection() 0 14 3
A handleForManager() 0 10 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace TMV\Laminas\Messenger\Bridge\Doctrine\Middleware;
6
7
use Doctrine\DBAL\Connection;
8
use Doctrine\DBAL\Exception;
9
use Doctrine\ORM\EntityManagerInterface;
10
use Symfony\Component\Messenger\Envelope;
11
use Symfony\Component\Messenger\Middleware\StackInterface;
12
use Symfony\Component\Messenger\Stamp\ConsumedByWorkerStamp;
13
14
/**
15
 * @final
16
 */
17
class DoctrinePingConnectionMiddleware extends AbstractDoctrineMiddleware
18
{
19
    protected function handleForManager(
20
        EntityManagerInterface $entityManager,
21
        Envelope $envelope,
22
        StackInterface $stack
23
    ): Envelope {
24
        if (null !== $envelope->last(ConsumedByWorkerStamp::class)) {
25
            $this->pingConnection($entityManager);
26
        }
27
28
        return $stack->next()->handle($envelope, $stack);
29
    }
30
31
    private function pingConnection(EntityManagerInterface $entityManager): void
32
    {
33
        $connection = $entityManager->getConnection();
34
35
        try {
36
            $this->executeDummySql($connection);
37
        } catch (Exception) {
38
            $connection->close();
39
            // Attempt to reestablish the lazy connection by sending another query.
40
            $this->executeDummySql($connection);
41
        }
42
43
        if (! $entityManager->isOpen()) {
44
            $this->managerRegistry->resetManager($this->entityManagerName);
45
        }
46
    }
47
48
    /**
49
     * @throws Exception
50
     */
51
    private function executeDummySql(Connection $connection): void
52
    {
53
        $connection->executeQuery($connection->getDatabasePlatform()->getDummySelectSQL());
54
    }
55
}
56