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