Completed
Push — master ( b539f5...2b6674 )
by Philip
25:54 queued 57s
created

TransactionManager::rollbackTransaction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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