SimpleTransactionManager::rollback()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 7
cts 7
cp 1
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2
1
<?php
2
3
namespace RemiSan\TransactionManager;
4
5
use RemiSan\TransactionManager\Exception\BeginException;
6
use RemiSan\TransactionManager\Exception\NoRunningTransactionException;
7
use RemiSan\TransactionManager\Exception\TransactionException;
8
9
class SimpleTransactionManager implements TransactionManager
10
{
11
    /**
12
     * @var Transactional[]
13
     */
14
    private $items;
15
16
    /**
17
     * @var bool
18
     */
19
    private $running;
20
21
    /**
22
     * Constructor.
23
     *
24
     * @param Transactional[] $items
25
     */
26 45
    public function __construct(array $items = [])
27
    {
28 45
        $this->items = $items;
29 45
        $this->reset();
30 45
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35 27
    public function addTransactionalItem(Transactional $item)
36
    {
37 27
        if ($this->running) {
38 3
            throw new TransactionException('You cannot add a transactional item during a running transaction');
39
        }
40
41 27
        $this->items[] = $item;
42 27
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47 30
    public function beginTransaction()
48
    {
49 30
        if ($this->running) {
50 3
            throw new BeginException('Transaction already running');
51
        }
52
53 30
        if (count($this->items) === 0) {
54 3
            throw new BeginException('No transaction to start');
55
        }
56
57 27
        foreach ($this->items as $item) {
58 27
            $item->beginTransaction();
59 27
        }
60
61 27
        $this->running = true;
62 27
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67 9
    public function commit()
68
    {
69 9
        $this->checkTransaction();
70
71 6
        foreach ($this->items as $item) {
72 6
            $item->commit();
73 6
        }
74
75 6
        $this->reset();
76 6
    }
77
78
    /**
79
     * {@inheritdoc}
80
     */
81 9
    public function rollback()
82
    {
83 9
        $this->checkTransaction();
84
85 6
        foreach ($this->items as $item) {
86 6
            $item->rollback();
87 6
        }
88
89 6
        $this->reset();
90 6
    }
91
92
    /**
93
     * Check if there's a transaction running.
94
     *
95
     * @throws NoRunningTransactionException
96
     */
97 18
    private function checkTransaction()
98
    {
99 18
        if (!$this->running) {
100 6
            throw new NoRunningTransactionException('No transaction running');
101
        }
102 12
    }
103
104
    /**
105
     * Reset the transaction.
106
     */
107 45
    protected function reset()
108
    {
109 45
        $this->running = false;
110 45
    }
111
}
112