Completed
Push — master ( 8fee6e...874644 )
by Philip
24:56
created

TransactionManager::isInTransaction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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