TransactionPDO   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 75
rs 10
c 0
b 0
f 0
wmc 11
lcom 1
cbo 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A hasSavepoint() 0 4 1
A beginTransaction() 0 10 3
A commit() 0 10 3
A rollBack() 0 14 4
1
<?php
2
3
namespace League\Database\Driver;
4
5
use PDO;
6
use PDOException;
7
8
class TransactionPDO extends PDO
9
{
10
    /**
11
     * @var array   Database drivers that support SAVEPOINT * statements.
12
     */
13
    protected static $supportedDrivers = ['pgsql', 'mysql'];
14
15
    /**
16
     * @var int     Current transaction depth
17
     */
18
    protected $transactionDepth = 0;
19
20
    /**
21
     * Test if database driver support savepoints
22
     *
23
     * @return bool
24
     */
25
    protected function hasSavepoint() : bool
26
    {
27
        return in_array($this->getAttribute(PDO::ATTR_DRIVER_NAME), self::$supportedDrivers, true);
28
    }
29
30
    /**
31
     * Start transaction
32
     *
33
     * @return bool|void
34
     */
35
    public function beginTransaction()
36
    {
37
        if ($this->transactionDepth == 0 || !$this->hasSavepoint()) {
38
            parent::beginTransaction();
39
        } else {
40
            $this->exec("SAVEPOINT LEVEL{$this->transactionDepth}");
41
        }
42
43
        $this->transactionDepth++;
44
    }
45
46
    /**
47
     * Commit current transaction
48
     *
49
     * @return bool|void
50
     */
51
    public function commit()
52
    {
53
        $this->transactionDepth--;
54
55
        if ($this->transactionDepth == 0 || !$this->hasSavepoint()) {
56
            parent::commit();
57
        } else {
58
            $this->exec("RELEASE SAVEPOINT LEVEL{$this->transactionDepth}");
59
        }
60
    }
61
62
    /**
63
     * Rollback current transaction
64
     *
65
     * @throws \PDOException    if there is no transaction started
66
     * @return bool|void
67
     */
68
    public function rollBack()
69
    {
70
        if ($this->transactionDepth == 0) {
71
            throw new PDOException('Rollback error : There is no transaction started');
72
        }
73
74
        $this->transactionDepth--;
75
76
        if ($this->transactionDepth == 0 || !$this->hasSavepoint()) {
77
            parent::rollBack();
78
        } else {
79
            $this->exec("ROLLBACK TO SAVEPOINT LEVEL{$this->transactionDepth}");
80
        }
81
    }
82
}
83