Passed
Push — master ( 109e7c...79a79c )
by Thomas Mauro
02:15
created

DoctrinePingConnectionMiddleware   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 14
dl 0
loc 34
ccs 12
cts 12
cp 1
rs 10
c 1
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A pingConnection() 0 12 3
A handleForManager() 0 10 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace TMV\Laminas\Messenger\Middleware;
6
7
use Doctrine\ORM\EntityManagerInterface;
8
use Doctrine\Persistence\ManagerRegistry;
9
use Symfony\Component\Messenger\Envelope;
10
use Symfony\Component\Messenger\Middleware\StackInterface;
11
use Symfony\Component\Messenger\Stamp\ConsumedByWorkerStamp;
12
13
final class DoctrinePingConnectionMiddleware extends AbstractDoctrineMiddleware
14 3
{
15
    private string $query;
16
17
    public function __construct(ManagerRegistry $managerRegistry, string $entityManagerName, string $query = 'SELECT 1;')
18
    {
19 3
        parent::__construct($managerRegistry, $entityManagerName);
20 2
        $this->query = $query;
21
    }
22
23 3
    protected function handleForManager(
24
        EntityManagerInterface $entityManager,
25
        Envelope $envelope,
26 2
        StackInterface $stack
27
    ): Envelope {
28 2
        if (null !== $envelope->last(ConsumedByWorkerStamp::class)) {
29
            $this->pingConnection($entityManager);
30 2
        }
31 2
32 2
        return $stack->next()->handle($envelope, $stack);
33
    }
34
35 2
    private function pingConnection(EntityManagerInterface $entityManager): void
36 2
    {
37
        $connection = $entityManager->getConnection();
38 2
39
        try {
40
            $connection->executeQuery($this->query);
41
        } catch (\Throwable $exception) {
42
            $connection->close();
43
        }
44
45
        if (! $entityManager->isOpen()) {
46
            $this->managerRegistry->resetManager($this->entityManagerName);
47
        }
48
    }
49
}
50