Completed
Push — master ( e9374c...cb2a7b )
by Ross
01:50
created

TransactionMiddleware::rollbackTransaction()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 1
Metric Value
c 1
b 1
f 1
dl 0
loc 9
rs 9.6666
cc 3
eloc 5
nc 2
nop 0
1
<?php
2
namespace League\Tactician\Doctrine\ORM;
3
4
use Doctrine\ORM\EntityManagerInterface;
5
use League\Tactician\Middleware;
6
use Exception;
7
use Throwable;
8
9
/**
10
 * Wraps command execution inside a Doctrine ORM transaction
11
 */
12
class TransactionMiddleware implements Middleware
13
{
14
    /**
15
     * @var EntityManagerInterface
16
     */
17
    private $entityManager;
18
19
    /**
20
     * @param EntityManagerInterface $entityManager
21
     */
22
    public function __construct(EntityManagerInterface $entityManager)
23
    {
24
        $this->entityManager = $entityManager;
25
    }
26
27
    /**
28
     * Executes the given command and optionally returns a value
29
     *
30
     * @param object $command
31
     * @param callable $next
32
     * @return mixed
33
     * @throws Throwable
34
     * @throws Exception
35
     */
36
    public function execute($command, callable $next)
37
    {
38
        $this->entityManager->beginTransaction();
39
40
        try {
41
            $returnValue = $next($command);
42
43
            $this->entityManager->flush();
44
            $this->entityManager->commit();
45
        } catch (Exception $e) {
46
            $this->rollbackTransaction();
47
48
            throw $e;
49
        } catch (Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
50
            $this->rollbackTransaction();
51
52
            throw $e;
53
        }
54
55
        return $returnValue;
56
    }
57
58
    /**
59
     * Rollback the current transaction and close the entity manager when possible.
60
     */
61
    protected function rollbackTransaction()
62
    {
63
        $this->entityManager->rollback();
64
65
        $connection = $this->entityManager->getConnection();
66
        if (!$connection->isTransactionActive() || $connection->isRollbackOnly()) {
67
            $this->entityManager->close();
68
        }
69
    }
70
}
71