Reduce calls to MediaWikiServices::getInstance()
authorUmherirrender <umherirrender_de.wp@web.de>
Sat, 18 Aug 2018 04:02:39 +0000 (06:02 +0200)
committerUmherirrender <umherirrender_de.wp@web.de>
Sat, 18 Aug 2018 04:02:39 +0000 (06:02 +0200)
In some functions MediaWikiServices::getInstance() was called twices or
in loops. Extract the variable to reduce calls.

Change-Id: I2705db11d7a9ea73efb9b5a5c40747ab0b3ea36f

20 files changed:
includes/OutputPage.php
includes/Preferences.php
includes/api/ApiPageSet.php
includes/api/ApiQuerySearch.php
includes/cache/LinkBatch.php
includes/cache/MessageCache.php
includes/deferred/LinksUpdate.php
includes/deferred/SearchUpdate.php
includes/filerepo/LocalRepo.php
includes/filerepo/file/ForeignAPIFile.php
includes/logging/ProtectLogFormatter.php
includes/page/WikiPage.php
includes/search/SearchEngine.php
includes/skins/Skin.php
includes/specials/SpecialEditWatchlist.php
includes/specials/SpecialListgrouprights.php
includes/specials/SpecialSearch.php
includes/specials/SpecialWatchlist.php
includes/widget/search/SearchFormWidget.php
maintenance/orphans.php

index 20557e9..c8e18e0 100644 (file)
@@ -3060,6 +3060,7 @@ class OutputPage extends ContextSource {
                $curRevisionId = 0;
                $articleId = 0;
                $canonicalSpecialPageName = false; # T23115
+               $services = MediaWikiServices::getInstance();
 
                $title = $this->getTitle();
                $ns = $title->getNamespace();
@@ -3075,7 +3076,7 @@ class OutputPage extends ContextSource {
 
                if ( $ns == NS_SPECIAL ) {
                        list( $canonicalSpecialPageName, /*...*/ ) =
-                               MediaWikiServices::getInstance()->getSpecialPageFactory()->
+                               $services->getSpecialPageFactory()->
                                        resolveAlias( $title->getDBkey() );
                } elseif ( $this->canUseWikiPage() ) {
                        $wikiPage = $this->getWikiPage();
@@ -3141,7 +3142,7 @@ class OutputPage extends ContextSource {
                        $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
                }
 
-               $contLang = MediaWikiServices::getInstance()->getContentLanguage();
+               $contLang = $services->getContentLanguage();
                if ( $contLang->hasVariants() ) {
                        $vars['wgUserVariant'] = $contLang->getPreferredVariant();
                }
index d66da93..6d379dc 100644 (file)
@@ -35,11 +35,12 @@ class Preferences {
         * @return DefaultPreferencesFactory
         */
        protected static function getDefaultPreferencesFactory() {
+               $services = MediaWikiServices::getInstance();
                $authManager = AuthManager::singleton();
-               $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
-               $config = MediaWikiServices::getInstance()->getMainConfig();
+               $linkRenderer = $services->getLinkRenderer();
+               $config = $services->getMainConfig();
                $preferencesFactory = new DefaultPreferencesFactory(
-                       $config, MediaWikiServices::getInstance()->getContentLanguage(), $authManager,
+                       $config, $services->getContentLanguage(), $authManager,
                        $linkRenderer
                );
                return $preferencesFactory;
index 41358cb..26846f4 100644 (file)
@@ -1170,6 +1170,8 @@ class ApiPageSet extends ApiBase {
        private function processTitlesArray( $titles ) {
                $usernames = [];
                $linkBatch = new LinkBatch();
+               $services = MediaWikiServices::getInstance();
+               $contLang = $services->getContentLanguage();
 
                foreach ( $titles as $title ) {
                        if ( is_string( $title ) ) {
@@ -1197,7 +1199,6 @@ class ApiPageSet extends ApiBase {
                                $this->mInterwikiTitles[$unconvertedTitle] = $titleObj->getInterwiki();
                        } else {
                                // Variants checking
-                               $contLang = MediaWikiServices::getInstance()->getContentLanguage();
                                if (
                                        $this->mConvertTitles && $contLang->hasVariants() && !$titleObj->exists()
                                ) {
@@ -1217,7 +1218,7 @@ class ApiPageSet extends ApiBase {
                                                $this->mAllSpecials[$ns][$dbkey] = $this->mFakePageId;
                                                $target = null;
                                                if ( $ns === NS_SPECIAL && $this->mResolveRedirects ) {
-                                                       $spFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
+                                                       $spFactory = $services->getSpecialPageFactory();
                                                        $special = $spFactory->getPage( $dbkey );
                                                        if ( $special instanceof RedirectSpecialArticle ) {
                                                                // Only RedirectSpecialArticle is intended to redirect to an article, other kinds of
@@ -1264,7 +1265,7 @@ class ApiPageSet extends ApiBase {
                        }
                }
                // Get gender information
-               $genderCache = MediaWikiServices::getInstance()->getGenderCache();
+               $genderCache = $services->getGenderCache();
                $genderCache->doQuery( $usernames, __METHOD__ );
 
                return $linkBatch;
index d4f0396..b90dd5d 100644 (file)
@@ -399,13 +399,14 @@ class ApiQuerySearch extends ApiQueryGeneratorBase {
 
                // If we have more than one engine the list of available sorts is
                // difficult to represent. For now don't expose it.
-               $alternatives = MediaWiki\MediaWikiServices::getInstance()
+               $services = MediaWiki\MediaWikiServices::getInstance();
+               $alternatives = $services
                        ->getSearchEngineConfig()
                        ->getSearchTypes();
                if ( count( $alternatives ) == 1 ) {
                        $this->allowedParams['sort'] = [
                                ApiBase::PARAM_DFLT => 'relevance',
-                               ApiBase::PARAM_TYPE => MediaWiki\MediaWikiServices::getInstance()
+                               ApiBase::PARAM_TYPE => $services
                                        ->newSearchEngine()
                                        ->getValidSorts(),
                        ];
index 86dd338..7a0826e 100644 (file)
@@ -224,12 +224,13 @@ class LinkBatch {
                if ( $this->isEmpty() ) {
                        return false;
                }
+               $services = MediaWikiServices::getInstance();
 
-               if ( !MediaWikiServices::getInstance()->getContentLanguage()->needsGenderDistinction() ) {
+               if ( !$services->getContentLanguage()->needsGenderDistinction() ) {
                        return false;
                }
 
-               $genderCache = MediaWikiServices::getInstance()->getGenderCache();
+               $genderCache = $services->getGenderCache();
                $genderCache->doLinkBatch( $this->data, $this->caller );
 
                return true;
index f09b5bf..7a1b988 100644 (file)
@@ -107,15 +107,16 @@ class MessageCache {
        public static function singleton() {
                if ( self::$instance === null ) {
                        global $wgUseDatabaseMessages, $wgMsgCacheExpiry, $wgUseLocalMessageCache;
+                       $services = MediaWikiServices::getInstance();
                        self::$instance = new self(
-                               MediaWikiServices::getInstance()->getMainWANObjectCache(),
+                               $services->getMainWANObjectCache(),
                                wfGetMessageCacheStorage(),
                                $wgUseLocalMessageCache
-                                       ? MediaWikiServices::getInstance()->getLocalServerObjectCache()
+                                       ? $services->getLocalServerObjectCache()
                                        : new EmptyBagOStuff(),
                                $wgUseDatabaseMessages,
                                $wgMsgCacheExpiry,
-                               MediaWikiServices::getInstance()->getContentLanguage()
+                               $services->getContentLanguage()
                        );
                }
 
index ae3c660..5b1be6d 100644 (file)
@@ -584,10 +584,11 @@ class LinksUpdate extends DataUpdate implements EnqueueableDataUpdate {
                global $wgCategoryCollation;
                $diffs = array_diff_assoc( $this->mCategories, $existing );
                $arr = [];
+               $contLang = MediaWikiServices::getInstance()->getContentLanguage();
+               $collation = Collation::singleton();
                foreach ( $diffs as $name => $prefix ) {
                        $nt = Title::makeTitleSafe( NS_CATEGORY, $name );
-                       MediaWikiServices::getInstance()->getContentLanguage()->
-                               findVariantLink( $name, $nt, true );
+                       $contLang->findVariantLink( $name, $nt, true );
 
                        $type = MWNamespace::getCategoryLinkType( $this->mTitle->getNamespace() );
 
@@ -595,8 +596,7 @@ class LinksUpdate extends DataUpdate implements EnqueueableDataUpdate {
                        # things are forced to sort as '*' or something, they'll
                        # sort properly in the category rather than in page_id
                        # order or such.
-                       $sortkey = Collation::singleton()->getSortKey(
-                               $this->mTitle->getCategorySortkey( $prefix ) );
+                       $sortkey = $collation->getSortKey( $this->mTitle->getCategorySortkey( $prefix ) );
 
                        $arr[] = [
                                'cl_from' => $this->mId,
index 105877b..3625476 100644 (file)
@@ -75,13 +75,14 @@ class SearchUpdate implements DeferrableUpdate {
         * Perform actual update for the entry
         */
        public function doUpdate() {
-               $config = MediaWikiServices::getInstance()->getSearchEngineConfig();
+               $services = MediaWikiServices::getInstance();
+               $config = $services->getSearchEngineConfig();
 
                if ( $config->getConfig()->get( 'DisableSearchUpdate' ) || !$this->id ) {
                        return;
                }
 
-               $seFactory = MediaWikiServices::getInstance()->getSearchEngineFactory();
+               $seFactory = $services->getSearchEngineFactory();
                foreach ( $config->getSearchTypes() as $type ) {
                        $search = $seFactory->create( $type );
                        if ( !$search->supports( 'search-update' ) ) {
@@ -117,14 +118,16 @@ class SearchUpdate implements DeferrableUpdate {
         * @return string
         */
        public function updateText( $text, SearchEngine $se = null ) {
+               $services = MediaWikiServices::getInstance();
+               $contLang = $services->getContentLanguage();
                # Language-specific strip/conversion
-               $text = MediaWikiServices::getInstance()->getContentLanguage()->normalizeForSearch( $text );
-               $se = $se ?: MediaWikiServices::getInstance()->newSearchEngine();
+               $text = $contLang->normalizeForSearch( $text );
+               $se = $se ?: $services->newSearchEngine();
                $lc = $se->legalSearchChars() . '&#;';
 
                # Strip HTML markup
                $text = preg_replace( "/<\\/?\\s*[A-Za-z][^>]*?>/",
-                       ' ', MediaWikiServices::getInstance()->getContentLanguage()->lc( " " . $text . " " ) );
+                       ' ', $contLang->lc( " " . $text . " " ) );
                $text = preg_replace( "/(^|\\n)==\\s*([^\\n]+)\\s*==(\\s)/sD",
                        "\\1\\2 \\2 \\2\\3", $text ); # Emphasize headings
 
@@ -199,13 +202,14 @@ class SearchUpdate implements DeferrableUpdate {
         * @return string A stripped-down title string ready for the search index
         */
        private function getNormalizedTitle( SearchEngine $search ) {
+               $contLang = MediaWikiServices::getInstance()->getContentLanguage();
                $ns = $this->title->getNamespace();
                $title = $this->title->getText();
 
                $lc = $search->legalSearchChars() . '&#;';
-               $t = MediaWikiServices::getInstance()->getContentLanguage()->normalizeForSearch( $title );
+               $t = $contLang->normalizeForSearch( $title );
                $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
-               $t = MediaWikiServices::getInstance()->getContentLanguage()->lc( $t );
+               $t = $contLang->lc( $t );
 
                # Handle 's, s'
                $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
index 789ed4c..c889e56 100644 (file)
@@ -278,6 +278,7 @@ class LocalRepo extends FileRepo {
                $applyMatchingFiles = function ( ResultWrapper $res, &$searchSet, &$finalFiles )
                        use ( $fileMatchesSearch, $flags )
                {
+                       $contLang = MediaWikiServices::getInstance()->getContentLanguage();
                        $info = $this->getInfo();
                        foreach ( $res as $row ) {
                                $file = $this->newFileFromRow( $row );
@@ -286,8 +287,7 @@ class LocalRepo extends FileRepo {
                                $dbKeysLook = [ strtr( $file->getName(), ' ', '_' ) ];
                                if ( !empty( $info['initialCapital'] ) ) {
                                        // Search keys for "hi.png" and "Hi.png" should use the "Hi.png file"
-                                       $dbKeysLook[] = MediaWikiServices::getInstance()->getContentLanguage()->
-                                               lcfirst( $file->getName() );
+                                       $dbKeysLook[] = $contLang->lcfirst( $file->getName() );
                                }
                                foreach ( $dbKeysLook as $dbKey ) {
                                        if ( isset( $searchSet[$dbKey] )
index 2ed4853..fd3dc8b 100644 (file)
@@ -355,11 +355,12 @@ class ForeignAPIFile extends File {
        }
 
        function purgeDescriptionPage() {
+               $services = MediaWikiServices::getInstance();
                $url = $this->repo->getDescriptionRenderUrl(
-                       $this->getName(), MediaWikiServices::getInstance()->getContentLanguage()->getCode() );
+                       $this->getName(), $services->getContentLanguage()->getCode() );
                $key = $this->repo->getLocalCacheKey( 'RemoteFileDescription', 'url', md5( $url ) );
 
-               MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
+               $services->getMainWANObjectCache()->delete( $key );
        }
 
        /**
index 02a6972..ba02457 100644 (file)
@@ -150,9 +150,10 @@ class ProtectLogFormatter extends LogFormatter {
        public function formatParametersForApi() {
                $ret = parent::formatParametersForApi();
                if ( isset( $ret['details'] ) && is_array( $ret['details'] ) ) {
+                       $contLang = MediaWikiServices::getInstance()->getContentLanguage();
                        foreach ( $ret['details'] as &$detail ) {
                                if ( isset( $detail['expiry'] ) ) {
-                                       $detail['expiry'] = MediaWikiServices::getInstance()->getContentLanguage()->
+                                       $detail['expiry'] = $contLang->
                                                formatExpiry( $detail['expiry'], TS_ISO_8601, 'infinite' );
                                }
                        }
index c3df0e5..147c9f3 100644 (file)
@@ -2367,10 +2367,11 @@ class WikiPage implements Page, IDBAccessObject {
        public function protectDescriptionLog( array $limit, array $expiry ) {
                $protectDescriptionLog = '';
 
+               $dirMark = MediaWikiServices::getInstance()->getContentLanguage()->getDirMark();
                foreach ( array_filter( $limit ) as $action => $restrictions ) {
                        $expiryText = $this->formatExpiry( $expiry[$action] );
                        $protectDescriptionLog .=
-                               MediaWikiServices::getInstance()->getContentLanguage()->getDirMark() .
+                               $dirMark .
                                "[$action=$restrictions] ($expiryText)";
                }
 
index e3088c1..965a413 100644 (file)
@@ -264,8 +264,9 @@ abstract class SearchEngine {
         * @return SearchNearMatcher
         */
        protected static function defaultNearMatcher() {
-               $config = MediaWikiServices::getInstance()->getMainConfig();
-               return MediaWikiServices::getInstance()->newSearchEngine()->getNearMatcher( $config );
+               $services = MediaWikiServices::getInstance();
+               $config = $services->getMainConfig();
+               return $services->newSearchEngine()->getNearMatcher( $config );
        }
 
        /**
index 69168c6..43b3ec1 100644 (file)
@@ -1548,7 +1548,8 @@ abstract class Skin extends ContextSource {
                        $notice = $msg->plain();
                }
 
-               $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
+               $services = MediaWikiServices::getInstance();
+               $cache = $services->getMainWANObjectCache();
                $parsed = $cache->getWithSetCallback(
                        // Use the extra hash appender to let eg SSL variants separately cache
                        // Key is verified with md5 hash of unparsed wikitext
@@ -1560,7 +1561,7 @@ abstract class Skin extends ContextSource {
                        }
                );
 
-               $contLang = MediaWikiServices::getInstance()->getContentLanguage();
+               $contLang = $services->getContentLanguage();
                return Html::rawElement(
                        'div',
                        [
index 7013e40..083b3c0 100644 (file)
@@ -573,6 +573,7 @@ class SpecialEditWatchlist extends UnlistedSpecialPage {
                if ( count( $fields ) > 1 && $count > 30 ) {
                        $this->toc = Linker::tocIndent();
                        $tocLength = 0;
+                       $contLang = MediaWikiServices::getInstance()->getContentLanguage();
 
                        foreach ( $fields as $data ) {
                                # strip out the 'ns' prefix from the section name:
@@ -580,8 +581,7 @@ class SpecialEditWatchlist extends UnlistedSpecialPage {
 
                                $nsText = ( $ns == NS_MAIN )
                                        ? $this->msg( 'blanknamespace' )->escaped()
-                                       : htmlspecialchars( MediaWikiServices::getInstance()->getContentLanguage()->
-                                               getFormattedNsText( $ns ) );
+                                       : htmlspecialchars( $contLang->getFormattedNsText( $ns ) );
                                $this->toc .= Linker::tocLine( "editwatchlist-{$data['section']}", $nsText,
                                        $this->getLanguage()->formatNum( ++$tocLength ), 1 ) . Linker::tocLineEnd();
                        }
index 8802a38..1d10791 100644 (file)
@@ -162,16 +162,17 @@ class SpecialListGroupRights extends SpecialPage {
                );
                $linkRenderer = $this->getLinkRenderer();
                ksort( $namespaceProtection );
+               $validNamespaces = MWNamespace::getValidNamespaces();
+               $contLang = MediaWikiServices::getInstance()->getContentLanguage();
                foreach ( $namespaceProtection as $namespace => $rights ) {
-                       if ( !in_array( $namespace, MWNamespace::getValidNamespaces() ) ) {
+                       if ( !in_array( $namespace, $validNamespaces ) ) {
                                continue;
                        }
 
                        if ( $namespace == NS_MAIN ) {
                                $namespaceText = $this->msg( 'blanknamespace' )->text();
                        } else {
-                               $namespaceText = MediaWikiServices::getInstance()->getContentLanguage()->
-                                       convertNamespace( $namespace );
+                               $namespaceText = $contLang->convertNamespace( $namespace );
                        }
 
                        $out->addHTML(
index 78a54f5..513d276 100644 (file)
@@ -709,9 +709,10 @@ class SpecialSearch extends SpecialPage {
         */
        public function getSearchEngine() {
                if ( $this->searchEngine === null ) {
+                       $services = MediaWikiServices::getInstance();
                        $this->searchEngine = $this->searchEngineType ?
-                               MediaWikiServices::getInstance()->getSearchEngineFactory()->create( $this->searchEngineType ) :
-                               MediaWikiServices::getInstance()->newSearchEngine();
+                               $services->getSearchEngineFactory()->create( $this->searchEngineType ) :
+                               $services->newSearchEngine();
                }
 
                return $this->searchEngine;
index 5b48f4e..908183d 100644 (file)
@@ -493,9 +493,10 @@ class SpecialWatchlist extends ChangesListSpecialPage {
                $dbr = $this->getDB();
                $user = $this->getUser();
                $output = $this->getOutput();
+               $services = MediaWikiServices::getInstance();
 
                # Show a message about replica DB lag, if applicable
-               $lag = MediaWikiServices::getInstance()->getDBLoadBalancer()->safeGetLag( $dbr );
+               $lag = $services->getDBLoadBalancer()->safeGetLag( $dbr );
                if ( $lag > 0 ) {
                        $output->showLagWarning( $lag );
                }
@@ -535,7 +536,7 @@ class SpecialWatchlist extends ChangesListSpecialPage {
                if ( $this->getConfig()->get( 'RCShowWatchingUsers' )
                        && $user->getOption( 'shownumberswatching' )
                ) {
-                       $watchedItemStore = MediaWikiServices::getInstance()->getWatchedItemStore();
+                       $watchedItemStore = $services->getWatchedItemStore();
                }
 
                $s = $list->beginRecentChangesList();
index 735806b..7eb92fd 100644 (file)
@@ -238,14 +238,14 @@ class SearchFormWidget {
        protected function powerSearchBox( $term, array $opts ) {
                $rows = [];
                $activeNamespaces = $this->specialSearch->getNamespaces();
+               $langConverter = MediaWikiServices::getInstance()->getContentLanguage()->getConverter();
                foreach ( $this->searchConfig->searchableNamespaces() as $namespace => $name ) {
                        $subject = MWNamespace::getSubject( $namespace );
                        if ( !isset( $rows[$subject] ) ) {
                                $rows[$subject] = "";
                        }
 
-                       $name = MediaWikiServices::getInstance()->getContentLanguage()->getConverter()->
-                               convertNamespace( $namespace );
+                       $name = $langConverter->convertNamespace( $namespace );
                        if ( $name === '' ) {
                                $name = $this->specialSearch->msg( 'blanknamespace' )->text();
                        }
index fad4e7d..d47ca43 100644 (file)
@@ -104,9 +104,9 @@ class Orphans extends Maintenance {
                                'rev_id', 'rev_page', 'rev_timestamp', 'rev_user_text', 'rev_comment'
                        ) );
 
+                       $contLang = MediaWikiServices::getInstance()->getContentLanguage();
                        foreach ( $result as $row ) {
                                $comment = $commentStore->getComment( 'rev_comment', $row )->text;
-                               $contLang = MediaWikiServices::getInstance()->getContentLanguage();
                                if ( $comment !== '' ) {
                                        $comment = '(' . $contLang->truncateForVisual( $comment, 40 ) . ')';
                                }