Completed
Push — master ( 254e6f...be5479 )
by Philip
07:28
created

TransactionManager::commitTransaction()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.009

Importance

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