DoctrineTransactionMiddleware::handleForManager()   A
last analyzed

Complexity

Conditions 3
Paths 7

Size

Total Lines 26
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3.1105

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 13
c 1
b 0
f 0
nc 7
nop 3
dl 0
loc 26
ccs 10
cts 13
cp 0.7692
crap 3.1105
rs 9.8333
1
<?php
2
3
declare(strict_types=1);
4
5
namespace TMV\Messenger\Middleware;
6
7
use Doctrine\ORM\EntityManagerInterface;
8
use Symfony\Component\Messenger\Envelope;
9
use Symfony\Component\Messenger\Exception\HandlerFailedException;
10
use Symfony\Component\Messenger\Middleware\StackInterface;
11
use Symfony\Component\Messenger\Stamp\HandledStamp;
12
use Throwable;
13
14
class DoctrineTransactionMiddleware extends AbstractDoctrineMiddleware
15
{
16 2
    protected function handleForManager(
17
        EntityManagerInterface $entityManager,
18
        Envelope $envelope,
19
        StackInterface $stack
20
    ): Envelope {
21 2
        $entityManager->getConnection()->beginTransaction();
22
23
        try {
24 2
            $envelope = $stack->next()->handle($envelope, $stack);
25 1
            $entityManager->flush();
26 1
            $entityManager->getConnection()->commit();
27
28 1
            return $envelope;
29 1
        } catch (Throwable $exception) {
30 1
            $entityManager->getConnection()->rollBack();
31
32 1
            if ($exception instanceof HandlerFailedException) {
33
                // Remove all HandledStamp from the envelope so the retry will execute all handlers again.
34
                // When a handler fails, the queries of allegedly successful previous handlers just got rolled back.
35
                throw new HandlerFailedException(
36
                    $exception->getEnvelope()->withoutAll(HandledStamp::class),
37
                    $exception->getNestedExceptions()
38
                );
39
            }
40
41 1
            throw $exception;
42
        }
43
    }
44
}
45