Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
CentralDBManager
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
4 / 4
7
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 getConnection
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 getCentralDBName
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 filterIsCentral
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace MediaWiki\Extension\AbuseFilter;
4
5use Wikimedia\Rdbms\DBError;
6use Wikimedia\Rdbms\IDatabase;
7use Wikimedia\Rdbms\LBFactory;
8
9class CentralDBManager {
10    public const SERVICE_NAME = 'AbuseFilterCentralDBManager';
11
12    /** @var string|false */
13    private $dbName;
14
15    /**
16     * @param LBFactory $loadBalancerFactory
17     * @param string|false|null $dbName
18     * @param bool $filterIsCentral
19     */
20    public function __construct(
21        private readonly LBFactory $loadBalancerFactory,
22        $dbName,
23        private readonly bool $filterIsCentral
24    ) {
25        // Use false to agree with LoadBalancer
26        $this->dbName = $dbName ?: false;
27    }
28
29    /**
30     * @param int $index DB_PRIMARY/DB_REPLICA
31     * @return IDatabase
32     * @throws DBError
33     * @throws CentralDBNotAvailableException
34     */
35    public function getConnection( int $index ): IDatabase {
36        if ( !is_string( $this->dbName ) ) {
37            throw new CentralDBNotAvailableException( '$wgAbuseFilterCentralDB is not configured' );
38        }
39
40        return $this->loadBalancerFactory
41            ->getMainLB( $this->dbName )
42            ->getConnection( $index, [], $this->dbName );
43    }
44
45    /**
46     * @return string
47     * @throws CentralDBNotAvailableException
48     */
49    public function getCentralDBName(): string {
50        if ( !is_string( $this->dbName ) ) {
51            throw new CentralDBNotAvailableException( '$wgAbuseFilterCentralDB is not configured' );
52        }
53        return $this->dbName;
54    }
55
56    /**
57     * Whether this database is the central one.
58     * @todo Deprecate the config in favour of just checking whether the current DB is the same
59     *  as $wgAbuseFilterCentralDB.
60     * @return bool
61     */
62    public function filterIsCentral(): bool {
63        return $this->filterIsCentral;
64    }
65}