Completed
Push — master ( d9caba...686839 )
by Philip
08:01
created

TransactionManager::commitTransaction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
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()
25
    {
26 9
        $nestingLevel = $this->entityManager->getConnection()->getTransactionNestingLevel();
27 9
        if (1 === $nestingLevel) {
28 9
            $this->entityManager->flush();
29
        }
30 9
        $this->entityManager->commit();
31 9
    }
32
33
    public function rollbackTransaction()
34
    {
35
        $this->entityManager->rollback();
36
    }
37
38
    public function isInTransaction()
39
    {
40
        $hasTransaction = 0 !== $this->entityManager->getConnection()->getTransactionNestingLevel();
41
42
        return ($hasTransaction);
43
    }
44
45
    /**
46
     * @param callable $func
47
     *
48
     * @return mixed
49
     */
50 9
    public function transactional($func)
51
    {
52 9
        if (!is_callable($func)) {
53
            throw new \InvalidArgumentException('Expected argument of type "callable", got "' . gettype($func) . '"');
54
        }
55
56 9
        $this->beginTransaction();
57
58
        try {
59 9
            $return = call_user_func($func, $this);
60
61 9
            $this->commitTransaction();
62
63 9
            return $return;
64
        } catch (\Exception $e) {
65
            $this->entityManager->close();
66
            $this->rollbackTransaction();
67
68
            throw $e;
69
        }
70
    }
71
}
72