mediawiki-extensions-AbuseF.../includes/CentralDBManager.php
Daimona Eaytoy 1f8df50cb3 Add a service to retrieve the central DB
This is a thin wrapper around LBFactory and the global variable, that
can be injected in classes requiring it (no real class right now, but
that's going to change soon).

Also, remove some DWIM-style returns which made the code harder to
understand.

Change-Id: I1d28ad4a67f914103f3a17cda5f61b28070c7f1c
2020-10-31 12:32:46 +00:00

42 lines
1 KiB
PHP

<?php
namespace MediaWiki\Extension\AbuseFilter;
use Wikimedia\Rdbms\DBError;
use Wikimedia\Rdbms\IDatabase;
use Wikimedia\Rdbms\LBFactory;
class CentralDBManager {
public const SERVICE_NAME = 'AbuseFilterCentralDBManager';
/** @var LBFactory */
private $loadBalancerFactory;
/** @var string|null */
private $dbName;
/**
* @param LBFactory $loadBalancerFactory
* @param string|null $dbName
*/
public function __construct( LBFactory $loadBalancerFactory, ?string $dbName ) {
$this->loadBalancerFactory = $loadBalancerFactory;
$this->dbName = $dbName;
}
/**
* @param int $index DB_MASTER/DB_REPLICA
* @return IDatabase
* @throws DBError
* @throws CentralDBNotAvailableException
*/
public function getConnection( int $index ) : IDatabase {
if ( !is_string( $this->dbName ) ) {
throw new CentralDBNotAvailableException( '$wgAbuseFilterCentralDB is not configured' );
}
return $this->loadBalancerFactory
->getMainLB( $this->dbName )
->getConnectionRef( $index, [], $this->dbName );
}
}