Completed
Push — master ( 62ac1b...07c3ff )
by Philip
08:31
created

TransactionManager::commitTransaction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 0
crap 2
1
<?php
2
3
namespace Dontdrinkandroot\Repository;
4
5
use Doctrine\ORM\EntityManagerInterface;
6
7
class TransactionManager
8
{
9
    /**
10
     * @var EntityManagerInterface
11
     */
12
    private $entityManager;
13
14 10
    public function __construct(EntityManagerInterface $entityManager)
15
    {
16 10
        $this->entityManager = $entityManager;
17 10
    }
18
19 9
    public function beginTransaction()
20
    {
21 9
        $this->entityManager->beginTransaction();
22 9
    }
23
24 9
    public function commitTransaction(): bool
25
    {
26 9
        $nestingLevel = $this->entityManager->getConnection()->getTransactionNestingLevel();
27 9
        $flush = false;
28 9
        if (1 === $nestingLevel) {
29 9
            $flush = true;
30 9
            $this->entityManager->flush();
31
        }
32 9
        $this->entityManager->commit();
33
34 9
        return $flush;
35
    }
36
37
    public function rollbackTransaction()
38
    {
39
        $this->entityManager->rollback();
40
    }
41
42
    public function isInTransaction()
43
    {
44
        $hasTransaction = 0 !== $this->entityManager->getConnection()->getTransactionNestingLevel();
45
46
        return ($hasTransaction);
47
    }
48
49
    /**
50
     * @param callable $func
51
     *
52
     * @return mixed
53
     */
54 9
    public function transactional($func)
55
    {
56 9
        if (!is_callable($func)) {
57
            throw new \InvalidArgumentException('Expected argument of type "callable", got "' . gettype($func) . '"');
58
        }
59
60 9
        $this->beginTransaction();
61
62
        try {
63 9
            $return = call_user_func($func, $this);
64
65 9
            $this->commitTransaction();
66
67 9
            return $return;
68
        } catch (\Exception $e) {
69
            $this->entityManager->close();
70
            $this->rollbackTransaction();
71
72
            throw $e;
73
        }
74
    }
75
}
76