Completed
Push — master ( 7c0346...9ff857 )
by Philip
08:18
created

TransactionManager::rollbackTransaction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 0
cts 3
cp 0
cc 1
eloc 2
nc 1
nop 0
crap 2
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 20
    public function __construct(EntityManagerInterface $entityManager)
18
    {
19 20
        $this->entityManager = $entityManager;
20 20
    }
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 18
        if (1 === $nestingLevel) {
32 18
            $flush = true;
33 18
            $this->entityManager->flush();
34
        }
35 18
        $this->entityManager->commit();
36
37 18
        return $flush;
38
    }
39
40
    public function rollbackTransaction()
41
    {
42
        $this->entityManager->rollback();
43
    }
44
45
    public function isInTransaction()
46
    {
47
        $hasTransaction = 0 !== $this->entityManager->getConnection()->getTransactionNestingLevel();
48
49
        return ($hasTransaction);
50
    }
51
52
    /**
53
     * @param callable $func
54
     *
55
     * @return mixed
56
     */
57 18
    public function transactional($func)
58
    {
59 18
        if (!is_callable($func)) {
60
            throw new \InvalidArgumentException('Expected argument of type "callable", got "' . gettype($func) . '"');
61
        }
62
63 18
        $this->beginTransaction();
64
65
        try {
66 18
            $return = call_user_func($func, $this);
67
68 18
            $this->commitTransaction();
69
70 18
            return $return;
71
        } catch (\Exception $e) {
72
            $this->entityManager->close();
73
            $this->rollbackTransaction();
74
75
            throw $e;
76
        }
77
    }
78
}
79