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

TransactionManager   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 62.07%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 2
dl 0
loc 65
ccs 18
cts 29
cp 0.6207
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A beginTransaction() 0 4 1
A rollbackTransaction() 0 4 1
A isInTransaction() 0 6 1
A transactional() 0 21 3
A commitTransaction() 0 8 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