Passed
Branch master (fddfe5)
by y
03:08 queued 48s
created

Transaction::__destruct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 2
nc 2
nop 0
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
    use FactoryTrait;
20
21
    /**
22
     * @var bool
23
     */
24
    protected $committed = false;
25
26
    /**
27
     * @var DB
28
     */
29
    protected $db;
30
31
    /**
32
     * Begins the transaction/savepoint.
33
     *
34
     * @param DB $db
35
     */
36
    public function __construct (DB $db) {
37
        $this->db = $db;
38
        $db->beginTransaction();
39
    }
40
41
    /**
42
     * Rolls back if the instance wasn't committed.
43
     */
44
    public function __destruct () {
45
        if (!$this->committed) {
46
            $this->db->rollBack();
47
        }
48
    }
49
50
    /**
51
     * Commits the transaction/savepoint.
52
     *
53
     * This is safe to call multiple times, it won't have any effect after the first time.
54
     *
55
     * @return true
56
     */
57
    public function commit (): bool {
58
        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...
59
    }
60
61
    /**
62
     * @return bool
63
     */
64
    final public function wasCommitted (): bool {
65
        return $this->committed;
66
    }
67
}