Transaction.php
1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
namespace AC\Storage;
use LogicException;
use wpdb;
final class Transaction {
const START = 1;
const COMMIT = 2;
const ROLLBACK = 3;
/**
* @var bool
*/
private $started = false;
/**
* @param bool $start Will start a transaction on creation if true
*/
public function __construct( $start = true ) {
if ( $start === true ) {
$this->start();
}
}
/**
* @param integer $type
*/
private function statement( $type ) {
global $wpdb;
if ( ! $wpdb instanceof wpdb ) {
throw new LogicException( 'The WordPress database is not yet initialized.' );
}
switch ( $type ) {
case self::START:
$sql = 'START TRANSACTION';
break;
case self::COMMIT:
$sql = 'COMMIT';
break;
case self::ROLLBACK:
$sql = 'ROLLBACK';
break;
default:
throw new LogicException( sprintf( 'Found invalid transaction statement: %s.', $type ) );
}
$wpdb->hide_errors();
$wpdb->query( $sql );
}
/**
* Start a MySQL transaction
*/
public function start() {
if ( $this->started ) {
throw new LogicException( 'Transaction has started already.' );
}
$this->started = true;
$this->statement( self::START );
}
/**
* Commit a MySQL transaction
*/
public function commit() {
$this->statement( self::COMMIT );
}
/**
* Rollback a MySQL transaction
*/
public function rollback() {
$this->statement( self::ROLLBACK );
}
}