Transaction   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 10
c 2
b 0
f 0
dl 0
loc 54
rs 10
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A commit() 0 3 2
A wasCommitted() 0 3 1
A __construct() 0 4 1
A __destruct() 0 4 2
1
<?php
2
3
namespace Helix\DB;
4
5
use Helix\DB;
6
7
/**
8
 * Scoped transaction/savepoint.
9
 *
10
 * If the instance isn't committed before it loses scope, it's rolled back.
11
 * There is no `rollback()` method.
12
 *
13
 * In order to ensure proper destruction, the instance MUST NOT leave the scope it's created in.
14
 *
15
 * @method static static factory(DB $db)
16
 */
17
class Transaction
18
{
19
20
    use FactoryTrait;
21
22
    /**
23
     * @var bool
24
     */
25
    protected $committed = false;
26
27
    /**
28
     * @var DB
29
     */
30
    protected $db;
31
32
    /**
33
     * Begins the transaction/savepoint.
34
     *
35
     * @param DB $db
36
     */
37
    public function __construct(DB $db)
38
    {
39
        $this->db = $db;
40
        $db->beginTransaction();
41
    }
42
43
    /**
44
     * Rolls back if the instance wasn't committed.
45
     */
46
    public function __destruct()
47
    {
48
        if (!$this->committed) {
49
            $this->db->rollBack();
50
        }
51
    }
52
53
    /**
54
     * Commits the transaction/savepoint.
55
     *
56
     * This is safe to call multiple times, it won't have any effect after the first time.
57
     *
58
     * @return true
59
     */
60
    public function commit(): bool
61
    {
62
        return $this->committed or $this->committed = $this->db->commit();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->committed ...d = $this->db->commit() returns the type boolean which is incompatible with the documented return type true.
Loading history...
63
    }
64
65
    /**
66
     * @return bool
67
     */
68
    final public function wasCommitted(): bool
69
    {
70
        return $this->committed;
71
    }
72
}
73