Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
17.65% covered (danger)
17.65%
3 / 17
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
DatabaseLookup
17.65% covered (danger)
17.65%
3 / 17
50.00% covered (danger)
50.00%
1 / 2
8.03
0.00% covered (danger)
0.00%
0 / 1
 getDatabases
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
6
 getDBName
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace MediaWiki\MassMessage\Lookup;
4
5use MediaWiki\MassMessage\UrlHelper;
6use MediaWiki\MediaWikiServices;
7use MediaWiki\WikiMap\WikiMap;
8
9class DatabaseLookup {
10
11    /**
12     * Get a mapping from site domains to database names.
13     * Requires $wgConf to be set up properly.
14     * Tries to read from cache if possible.
15     *
16     * @return array
17     */
18    public static function getDatabases() {
19        $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
20
21        return $cache->getWithSetCallback(
22            $cache->makeGlobalKey( 'massmessage', 'urltodb' ),
23            $cache::TTL_HOUR,
24            static function () {
25                global $wgConf;
26
27                $dbs = $wgConf->getLocalDatabases();
28                $mapping = [];
29                foreach ( $dbs as $dbname ) {
30                    $url = WikiMap::getWiki( $dbname )->getCanonicalServer();
31                    $site = UrlHelper::getBaseUrl( $url );
32                    $mapping[$site] = $dbname;
33                }
34                return $mapping;
35            }
36        );
37    }
38
39    /**
40     * Get database name from URL hostname or null if nothing is found.
41     *
42     * @param string $host
43     * @return string|null
44     */
45    public static function getDBName( $host ) {
46        $configuredAliases = MediaWikiServices::getInstance()->getMainConfig()->get( 'MassMessageWikiAliases' );
47        $mapping = self::getDatabases();
48        return $mapping[$host] ?? $configuredAliases[$host] ?? null;
49    }
50}