Merge "Improve docs for Title::getInternalURL/getCanonicalURL"
[lhc/web/wiklou.git] / includes / deferred / AutoCommitUpdate.php
1 <?php
2
3 use Wikimedia\Rdbms\IDatabase;
4
5 /**
6 * Deferrable Update for closure/callback updates that should use auto-commit mode
7 * @since 1.28
8 */
9 class AutoCommitUpdate implements DeferrableUpdate, DeferrableCallback {
10 /** @var IDatabase */
11 private $dbw;
12 /** @var string */
13 private $fname;
14 /** @var callable|null */
15 private $callback;
16
17 /**
18 * @param IDatabase $dbw DB handle; update aborts if a transaction now this rolls back
19 * @param string $fname Caller name (usually __METHOD__)
20 * @param callable $callback Callback that takes (IDatabase, method name string)
21 * @param IDatabase[] $conns Abort if a transaction now on one of these rolls back [optional]
22 */
23 public function __construct( IDatabase $dbw, $fname, callable $callback, array $conns = [] ) {
24 $this->dbw = $dbw;
25 $this->fname = $fname;
26 $this->callback = $callback;
27 // Register DB connections for which uncommitted changes are related to this update
28 $conns[] = $dbw;
29 foreach ( $conns as $conn ) {
30 if ( $conn->trxLevel() ) {
31 $conn->onTransactionResolution( [ $this, 'cancelOnRollback' ], $fname );
32 }
33 }
34 }
35
36 public function doUpdate() {
37 if ( !$this->callback ) {
38 return;
39 }
40
41 $autoTrx = $this->dbw->getFlag( DBO_TRX );
42 $this->dbw->clearFlag( DBO_TRX );
43 try {
44 /** @var Exception $e */
45 $e = null;
46 ( $this->callback )( $this->dbw, $this->fname );
47 } catch ( Exception $e ) {
48 }
49 if ( $autoTrx ) {
50 $this->dbw->setFlag( DBO_TRX );
51 }
52 if ( $e ) {
53 throw $e;
54 }
55 }
56
57 /**
58 * @private This method is public so that it works with onTransactionResolution()
59 * @param int $trigger
60 */
61 public function cancelOnRollback( $trigger ) {
62 if ( $trigger === IDatabase::TRIGGER_ROLLBACK ) {
63 $this->callback = null;
64 }
65 }
66
67 public function getOrigin() {
68 return $this->fname;
69 }
70 }