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

Transaction   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

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

4 Methods

Rating   Name   Duplication   Size   Complexity  
A commit() 0 2 2
A wasCommitted() 0 2 1
A __construct() 0 3 1
A __destruct() 0 3 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
    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
}