From 485f66f1744fea056e20a5bef619989bf1749202 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Bartosz=20Dziewo=C5=84ski?= Date: Sat, 7 Oct 2017 00:17:58 +0200 Subject: [PATCH] Use PHP 7 '??' operator instead of '?:' with 'isset()' where convenient Find: /isset\(\s*([^()]+?)\s*\)\s*\?\s*\1\s*:\s*/ Replace with: '\1 ?? ' (Everywhere except includes/PHPVersionCheck.php) (Then, manually fix some line length and indentation issues) Then manually reviewed the replacements for cases where confusing operator precedence would result in incorrect results (fixing those in I478db046a1cc162c6767003ce45c9b56270f3372). Change-Id: I33b421c8cb11cdd4ce896488c9ff5313f03a38cf --- includes/AjaxDispatcher.php | 4 +- includes/Block.php | 2 +- includes/CommentStore.php | 2 +- includes/EditPage.php | 6 +- includes/FauxRequest.php | 2 +- includes/GlobalFunctions.php | 4 +- includes/Html.php | 6 +- includes/Linker.php | 6 +- includes/MWNamespace.php | 4 +- includes/MediaWiki.php | 2 +- includes/NoLocalSettings.php | 2 +- includes/OutputPage.php | 10 +-- includes/PrefixSearch.php | 2 +- includes/Revision.php | 8 +-- includes/ServiceWiring.php | 4 +- includes/Storage/RevisionStore.php | 28 ++++----- includes/Title.php | 6 +- includes/WebRequest.php | 9 ++- includes/WikiMap.php | 2 +- includes/actions/HistoryAction.php | 4 +- includes/api/ApiAuthManagerHelper.php | 2 +- includes/api/ApiBase.php | 59 ++++++------------ includes/api/ApiCSPReport.php | 4 +- includes/api/ApiErrorFormatter.php | 2 +- includes/api/ApiFeedWatchlist.php | 4 +- includes/api/ApiFormatXml.php | 16 ++--- includes/api/ApiHelp.php | 22 ++----- includes/api/ApiModuleManager.php | 2 +- includes/api/ApiOptions.php | 4 +- includes/api/ApiParamInfo.php | 8 +-- includes/api/ApiQueryBacklinksprop.php | 2 +- includes/api/ApiQueryExternalLinks.php | 2 +- includes/api/ApiQuerySiteinfo.php | 8 +-- includes/api/ApiQueryUserContribs.php | 4 +- includes/api/ApiResult.php | 8 +-- includes/api/ApiRsd.php | 2 +- includes/api/ApiUndelete.php | 2 +- includes/api/ApiUpload.php | 4 +- includes/api/ApiUserrights.php | 2 +- includes/api/SearchApi.php | 2 +- includes/auth/AuthManager.php | 2 +- ...asswordSecondaryAuthenticationProvider.php | 2 +- .../ThrottlePreAuthenticationProvider.php | 3 +- includes/cache/GenderCache.php | 2 +- includes/cache/MessageCache.php | 2 +- includes/cache/UserCache.php | 4 +- includes/changes/ChangesList.php | 4 +- includes/changes/ChangesListFilterGroup.php | 2 +- includes/changes/EnhancedChangesList.php | 6 +- includes/changes/RecentChange.php | 22 +++---- includes/changetags/ChangeTags.php | 2 +- includes/clientpool/SquidPurgeClient.php | 2 +- includes/debug/logger/MonologSpi.php | 4 +- .../debug/logger/monolog/LineFormatter.php | 2 +- includes/externalstore/ExternalStoreDB.php | 6 +- .../externalstore/ExternalStoreMwstore.php | 2 +- includes/filebackend/FileBackendGroup.php | 14 ++--- includes/filerepo/FileRepo.php | 32 ++++------ includes/filerepo/ForeignAPIRepo.php | 2 +- includes/filerepo/RepoGroup.php | 2 +- includes/filerepo/file/File.php | 2 +- includes/filerepo/file/ForeignAPIFile.php | 8 +-- includes/filerepo/file/LocalFile.php | 12 ++-- includes/gallery/TraditionalImageGallery.php | 2 +- includes/htmlform/HTMLForm.php | 12 ++-- includes/htmlform/HTMLFormElement.php | 4 +- includes/htmlform/HTMLFormField.php | 6 +- includes/htmlform/fields/HTMLExpiryField.php | 2 +- includes/htmlform/fields/HTMLFloatField.php | 2 +- .../htmlform/fields/HTMLFormFieldCloner.php | 12 +--- .../fields/HTMLSelectAndOtherField.php | 5 +- .../fields/HTMLSelectOrOtherField.php | 4 +- .../htmlform/fields/HTMLSizeFilterField.php | 2 +- .../htmlform/fields/HTMLTextAreaField.php | 6 +- includes/htmlform/fields/HTMLTextField.php | 6 +- includes/import/WikiImporter.php | 4 +- includes/installer/CliInstaller.php | 2 +- .../installer/WebInstallerExistingWiki.php | 4 +- includes/interwiki/ClassicInterwikiLookup.php | 8 +-- includes/jobqueue/Job.php | 12 +--- includes/jobqueue/JobQueue.php | 12 ++-- includes/jobqueue/JobQueueDB.php | 2 +- includes/jobqueue/JobQueueFederated.php | 8 +-- includes/jobqueue/JobQueueRedis.php | 2 +- includes/jobqueue/JobQueueSecondTestQueue.php | 2 +- includes/jobqueue/JobRunner.php | 6 +- includes/jobqueue/JobSpecification.php | 8 +-- .../aggregator/JobQueueAggregatorRedis.php | 4 +- includes/jobqueue/jobs/DeleteLinksJob.php | 2 +- includes/jobqueue/jobs/HTMLCacheUpdateJob.php | 4 +- .../jobqueue/jobs/PublishStashedFileJob.php | 2 +- includes/jobqueue/utils/BacklinkJobUtils.php | 2 +- includes/libs/HttpStatus.php | 2 +- includes/libs/JavaScriptMinifier.php | 2 +- includes/libs/MappedIterator.php | 2 +- includes/libs/MultiHttpClient.php | 10 +-- includes/libs/Timing.php | 4 +- includes/libs/UDPTransport.php | 4 +- includes/libs/composer/ComposerInstalled.php | 6 +- includes/libs/composer/ComposerLock.php | 6 +- includes/libs/filebackend/FSFileBackend.php | 4 +- includes/libs/filebackend/FileBackend.php | 31 ++++------ .../filebackend/FileBackendMultiWrite.php | 8 +-- .../libs/filebackend/FileBackendStore.php | 12 ++-- includes/libs/filebackend/FileOpBatch.php | 2 +- .../libs/filebackend/HTTPFileStreamer.php | 8 +-- .../libs/filebackend/SwiftFileBackend.php | 56 +++++------------ .../filebackend/filejournal/FileJournal.php | 2 +- includes/libs/filebackend/fileop/FileOp.php | 2 +- includes/libs/lockmanager/DBLockManager.php | 4 +- includes/libs/lockmanager/LockManager.php | 4 +- includes/libs/lockmanager/MemcLockManager.php | 2 +- includes/libs/mime/MimeAnalyzer.php | 22 ++----- includes/libs/mime/XmlTypeCheck.php | 4 +- includes/libs/objectcache/BagOStuff.php | 8 +-- includes/libs/objectcache/HashBagOStuff.php | 2 +- includes/libs/objectcache/MemcachedClient.php | 14 ++--- includes/libs/objectcache/RedisBagOStuff.php | 4 +- includes/libs/objectcache/WANObjectCache.php | 62 +++++++++---------- .../libs/objectcache/WANObjectCacheReaper.php | 8 +-- includes/libs/rdbms/ChronologyProtector.php | 4 +- includes/libs/rdbms/database/Database.php | 42 ++++++------- .../libs/rdbms/database/DatabaseDomain.php | 2 +- .../libs/rdbms/database/DatabaseMssql.php | 8 +-- .../libs/rdbms/database/DatabaseMysqlBase.php | 10 +-- .../libs/rdbms/database/DatabasePostgres.php | 8 +-- .../libs/rdbms/database/DatabaseSqlite.php | 2 +- includes/libs/rdbms/field/MySQLField.php | 10 +-- includes/libs/rdbms/lbfactory/LBFactory.php | 48 ++++++-------- .../libs/rdbms/lbfactory/LBFactorySimple.php | 12 ++-- .../libs/rdbms/loadbalancer/LoadBalancer.php | 46 +++++--------- .../rdbms/loadbalancer/LoadBalancerSingle.php | 6 +- .../libs/rdbms/loadmonitor/LoadMonitor.php | 12 +--- .../rdbms/loadmonitor/LoadMonitorMySQL.php | 4 +- includes/libs/redis/RedisConnectionPool.php | 4 +- .../libs/virtualrest/VirtualRESTService.php | 2 +- includes/libs/xmp/XMP.php | 15 ++--- includes/logging/LogFormatter.php | 2 +- includes/logging/RightsLogFormatter.php | 10 ++- includes/mail/UserMailer.php | 7 +-- includes/media/BitmapMetadataHandler.php | 2 +- includes/media/DjVuHandler.php | 2 +- includes/media/MediaTransformOutput.php | 12 ++-- includes/media/SvgHandler.php | 2 +- .../media/TransformationalImageHandler.php | 2 +- includes/objectcache/ObjectCache.php | 10 +-- includes/objectcache/SqlBagOStuff.php | 6 +- includes/page/ImagePage.php | 5 +- includes/page/WikiPage.php | 4 +- includes/pager/IndexPager.php | 6 +- includes/pager/TablePager.php | 2 +- includes/parser/CoreParserFunctions.php | 2 +- includes/parser/LinkHolderArray.php | 2 +- includes/parser/Parser.php | 11 ++-- includes/parser/ParserOutput.php | 2 +- includes/parser/Preprocessor_DOM.php | 2 +- includes/parser/Preprocessor_Hash.php | 2 +- includes/parser/Sanitizer.php | 4 +- includes/password/Pbkdf2Password.php | 3 +- includes/poolcounter/PoolCounterWork.php | 4 +- .../preferences/DefaultPreferencesFactory.php | 8 +-- includes/profiler/ProfilerXhprof.php | 2 +- .../profiler/output/ProfilerOutputStats.php | 2 +- .../profiler/output/ProfilerOutputText.php | 7 +-- includes/registration/ExtensionProcessor.php | 8 +-- includes/resourceloader/ResourceLoader.php | 6 +- .../ResourceLoaderFileModule.php | 2 +- .../ResourceLoaderImageModule.php | 10 +-- .../ResourceLoaderOOUIImageModule.php | 2 +- .../ResourceLoaderWikiModule.php | 2 +- includes/revisiondelete/RevDelList.php | 4 +- includes/services/ServiceContainer.php | 2 +- .../ImmutableSessionProviderWithCookie.php | 8 +-- includes/session/PHPSessionHandler.php | 2 +- includes/session/SessionManager.php | 2 +- includes/shell/FirejailCommand.php | 2 +- includes/skins/BaseTemplate.php | 16 ++--- includes/skins/Skin.php | 4 +- .../specialpage/ChangesListSpecialPage.php | 8 +-- includes/specialpage/ImageQueryPage.php | 2 +- .../specialpage/LoginSignupSpecialPage.php | 3 +- includes/specialpage/QueryPage.php | 4 +- includes/specials/SpecialListgrouprights.php | 16 ++--- includes/specials/SpecialMediaStatistics.php | 4 +- includes/specials/SpecialNewpages.php | 2 +- includes/specials/SpecialPasswordReset.php | 4 +- includes/specials/SpecialUserrights.php | 2 +- includes/specials/SpecialVersion.php | 4 +- includes/specials/SpecialWantedcategories.php | 4 +- .../specials/formfields/UploadSourceField.php | 4 +- .../specials/forms/PreferencesFormLegacy.php | 2 +- .../specials/forms/PreferencesFormOOUI.php | 2 +- includes/specials/forms/UploadForm.php | 13 ++-- includes/specials/pagers/ContribsPager.php | 20 +++--- .../specials/pagers/DeletedContribsPager.php | 2 +- includes/specials/pagers/UsersPager.php | 2 +- includes/upload/UploadBase.php | 3 +- includes/user/BotPassword.php | 6 +- includes/user/User.php | 4 +- .../watcheditem/WatchedItemQueryService.php | 2 +- includes/widget/ComplexTitleInputWidget.php | 4 +- includes/widget/ExpiryInputWidget.php | 2 +- includes/widget/NamespaceInputWidget.php | 8 +-- languages/Language.php | 14 ++--- maintenance/cleanupInvalidDbKeys.php | 12 +--- maintenance/copyFileBackend.php | 4 +- maintenance/generateSitemap.php | 4 +- maintenance/mcc.php | 2 +- maintenance/renameDbPrefix.php | 4 +- maintenance/storage/moveToExternal.php | 2 +- maintenance/storage/testCompression.php | 2 +- maintenance/storage/trackBlobs.php | 2 +- maintenance/updateSpecialPages.php | 2 +- tests/parser/ParserTestRunner.php | 9 ++- tests/phpunit/MediaWikiTestCase.php | 8 +-- .../GlobalFunctions/wfUrlencodeTest.php | 4 +- tests/phpunit/includes/HtmlTest.php | 2 +- tests/phpunit/includes/PrefixSearchTest.php | 4 +- tests/phpunit/includes/TestUserRegistry.php | 4 +- tests/phpunit/includes/api/ApiBaseTest.php | 5 +- .../includes/api/ApiComparePagesTest.php | 2 +- tests/phpunit/includes/api/ApiMainTest.php | 6 +- .../includes/api/format/ApiFormatBaseTest.php | 2 +- .../includes/api/format/ApiFormatTestBase.php | 4 +- .../includes/api/generateRandomImages.php | 2 +- .../api/query/ApiQueryUserContribsTest.php | 2 +- .../phpunit/includes/auth/AuthManagerTest.php | 2 +- .../includes/cache/GenderCacheTest.php | 6 +- .../includes/db/DatabaseTestHelper.php | 6 +- .../libs/rdbms/database/DatabaseSQLTest.php | 34 +++++----- .../includes/logging/LogFormatterTestCase.php | 18 +++--- .../ResourceLoaderStartUpModuleTest.php | 2 +- ...AbstractChangesListSpecialPageTestCase.php | 2 +- tests/qunit/data/styleTest.css.php | 6 +- thumb.php | 6 +- 235 files changed, 635 insertions(+), 957 deletions(-) diff --git a/includes/AjaxDispatcher.php b/includes/AjaxDispatcher.php index 35b556df7b..5f825c8b5a 100644 --- a/includes/AjaxDispatcher.php +++ b/includes/AjaxDispatcher.php @@ -76,7 +76,7 @@ class AjaxDispatcher { switch ( $this->mode ) { case 'get': - $this->func_name = isset( $_GET["rs"] ) ? $_GET["rs"] : ''; + $this->func_name = $_GET["rs"] ?? ''; if ( !empty( $_GET["rsargs"] ) ) { $this->args = $_GET["rsargs"]; } else { @@ -84,7 +84,7 @@ class AjaxDispatcher { } break; case 'post': - $this->func_name = isset( $_POST["rs"] ) ? $_POST["rs"] : ''; + $this->func_name = $_POST["rs"] ?? ''; if ( !empty( $_POST["rsargs"] ) ) { $this->args = $_POST["rsargs"]; } else { diff --git a/includes/Block.php b/includes/Block.php index 2ce1f3ebfc..9567b06803 100644 --- a/includes/Block.php +++ b/includes/Block.php @@ -458,7 +458,7 @@ class Block { protected function initFromRow( $row ) { $this->setTarget( $row->ipb_address ); $this->setBlocker( User::newFromAnyId( - $row->ipb_by, $row->ipb_by_text, isset( $row->ipb_by_actor ) ? $row->ipb_by_actor : null + $row->ipb_by, $row->ipb_by_text, $row->ipb_by_actor ?? null ) ); $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp ); diff --git a/includes/CommentStore.php b/includes/CommentStore.php index e9b08e89dc..6b94d58e6c 100644 --- a/includes/CommentStore.php +++ b/includes/CommentStore.php @@ -261,7 +261,7 @@ class CommentStore { private function getCommentInternal( IDatabase $db = null, $key, $row, $fallback = false ) { $row = (array)$row; if ( array_key_exists( "{$key}_text", $row ) && array_key_exists( "{$key}_data", $row ) ) { - $cid = isset( $row["{$key}_cid"] ) ? $row["{$key}_cid"] : null; + $cid = $row["{$key}_cid"] ?? null; $text = $row["{$key}_text"]; $data = $row["{$key}_data"]; } elseif ( $this->stage === MIGRATION_OLD ) { diff --git a/includes/EditPage.php b/includes/EditPage.php index bd44cf7416..13d1623d08 100644 --- a/includes/EditPage.php +++ b/includes/EditPage.php @@ -1578,7 +1578,7 @@ class EditPage { $query = $query . '&' . $extraQueryRedirect; } } - $anchor = isset( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : ''; + $anchor = $resultDetails['sectionanchor'] ?? ''; $out->redirect( $this->mTitle->getFullURL( $query ) . $anchor ); return false; @@ -4195,7 +4195,7 @@ ERROR; $checkboxesDef = $this->getCheckboxesDefinition( $checked ); foreach ( $checkboxesDef as $name => $options ) { - $legacyName = isset( $options['legacy-name'] ) ? $options['legacy-name'] : $name; + $legacyName = $options['legacy-name'] ?? $name; $title = null; $accesskey = null; @@ -4221,7 +4221,7 @@ ERROR; 'align' => 'inline', 'label' => new OOUI\HtmlSnippet( $this->context->msg( $options['label-message'] )->parse() ), 'title' => $title, - 'id' => isset( $options['label-id'] ) ? $options['label-id'] : null, + 'id' => $options['label-id'] ?? null, ] ); } diff --git a/includes/FauxRequest.php b/includes/FauxRequest.php index 2f7f75b4d7..ecbc6e3373 100644 --- a/includes/FauxRequest.php +++ b/includes/FauxRequest.php @@ -121,7 +121,7 @@ class FauxRequest extends WebRequest { $prefix = $wgCookiePrefix; } $name = $prefix . $key; - return isset( $this->cookies[$name] ) ? $this->cookies[$name] : $default; + return $this->cookies[$name] ?? $default; } /** diff --git a/includes/GlobalFunctions.php b/includes/GlobalFunctions.php index a9cad25fee..72fda556c6 100644 --- a/includes/GlobalFunctions.php +++ b/includes/GlobalFunctions.php @@ -1516,7 +1516,7 @@ function wfBacktrace( $raw = null ) { $frames = array_map( function ( $frame ) use ( $frameFormat ) { $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-'; - $line = isset( $frame['line'] ) ? $frame['line'] : '-'; + $line = $frame['line'] ?? '-'; $call = $frame['function']; if ( !empty( $frame['class'] ) ) { $call = $frame['class'] . $frame['type'] . $call; @@ -2241,7 +2241,7 @@ function wfShellExec( $cmd, &$retval = null, $environ = [], } $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr']; - $profileMethod = isset( $options['profileMethod'] ) ? $options['profileMethod'] : wfGetCaller(); + $profileMethod = $options['profileMethod'] ?? wfGetCaller(); try { $result = Shell::command( [] ) diff --git a/includes/Html.php b/includes/Html.php index 019e0785f9..2ca52291b5 100644 --- a/includes/Html.php +++ b/includes/Html.php @@ -391,8 +391,8 @@ class Html { unset( $attribs['type'] ); } if ( $element === 'input' ) { - $type = isset( $attribs['type'] ) ? $attribs['type'] : null; - $value = isset( $attribs['value'] ) ? $attribs['value'] : null; + $type = $attribs['type'] ?? null; + $value = $attribs['value'] ?? null; if ( $type === 'checkbox' || $type === 'radio' ) { // The default value for checkboxes and radio buttons is 'on' // not ''. By stripping value="" we break radio boxes that @@ -925,7 +925,7 @@ class Html { if ( isset( $params['label'] ) ) { $ret .= self::element( 'label', [ - 'for' => isset( $selectAttribs['id'] ) ? $selectAttribs['id'] : null, + 'for' => $selectAttribs['id'] ?? null, ], $params['label'] ) . ' '; } diff --git a/includes/Linker.php b/includes/Linker.php index 5cdbfee140..3ee442d104 100644 --- a/includes/Linker.php +++ b/includes/Linker.php @@ -338,7 +338,7 @@ class Linker { } // Clean up parameters - $page = isset( $handlerParams['page'] ) ? $handlerParams['page'] : false; + $page = $handlerParams['page'] ?? false; if ( !isset( $frameParams['align'] ) ) { $frameParams['align'] = ''; } @@ -442,7 +442,7 @@ class Linker { $params = [ 'alt' => $frameParams['alt'], 'title' => $frameParams['title'], - 'valign' => isset( $frameParams['valign'] ) ? $frameParams['valign'] : false, + 'valign' => $frameParams['valign'] ?? false, 'img-class' => $frameParams['class'] ]; if ( isset( $frameParams['border'] ) ) { $params['img-class'] .= ( $params['img-class'] !== '' ? ' ' : '' ) . 'thumbborder'; @@ -535,7 +535,7 @@ class Linker { ) { $exists = $file && $file->exists(); - $page = isset( $handlerParams['page'] ) ? $handlerParams['page'] : false; + $page = $handlerParams['page'] ?? false; if ( !isset( $frameParams['align'] ) ) { $frameParams['align'] = 'right'; } diff --git a/includes/MWNamespace.php b/includes/MWNamespace.php index f2f98ba29c..bfbd557923 100644 --- a/includes/MWNamespace.php +++ b/includes/MWNamespace.php @@ -472,9 +472,7 @@ class MWNamespace { */ public static function getNamespaceContentModel( $index ) { global $wgNamespaceContentModels; - return isset( $wgNamespaceContentModels[$index] ) - ? $wgNamespaceContentModels[$index] - : null; + return $wgNamespaceContentModels[$index] ?? null; } /** diff --git a/includes/MediaWiki.php b/includes/MediaWiki.php index 459a7e1dcc..1642377e34 100644 --- a/includes/MediaWiki.php +++ b/includes/MediaWiki.php @@ -939,7 +939,7 @@ class MediaWiki { try { $statsdServer = explode( ':', $config->get( 'StatsdServer' ) ); $statsdHost = $statsdServer[0]; - $statsdPort = isset( $statsdServer[1] ) ? $statsdServer[1] : 8125; + $statsdPort = $statsdServer[1] ?? 8125; $statsdSender = new SocketSender( $statsdHost, $statsdPort ); $statsdClient = new SamplingStatsdClient( $statsdSender, true, false ); $statsdClient->setSamplingRates( $config->get( 'StatsdSamplingRates' ) ); diff --git a/includes/NoLocalSettings.php b/includes/NoLocalSettings.php index 46e9630f34..f6f4cd3a3e 100644 --- a/includes/NoLocalSettings.php +++ b/includes/NoLocalSettings.php @@ -52,7 +52,7 @@ try { echo $templateParser->processTemplate( 'NoLocalSettings', [ - 'wgVersion' => ( isset( $wgVersion ) ? $wgVersion : 'VERSION' ), + 'wgVersion' => ( $wgVersion ?? 'VERSION' ), 'path' => $path, 'localSettingsExists' => file_exists( MW_CONFIG_FILE ), 'installerStarted' => $installerStarted diff --git a/includes/OutputPage.php b/includes/OutputPage.php index d76ed771df..c51f6f8ec2 100644 --- a/includes/OutputPage.php +++ b/includes/OutputPage.php @@ -642,9 +642,7 @@ class OutputPage extends ContextSource { // Register a callback for $this->contentOverrides on the first call $this->addContentOverrideCallback( function ( LinkTarget $target ) { $key = $target->getNamespace() . ':' . $target->getDBkey(); - return isset( $this->contentOverrides[$key] ) - ? $this->contentOverrides[$key] - : null; + return $this->contentOverrides[$key] ?? null; } ); } @@ -1516,9 +1514,7 @@ class OutputPage extends ContextSource { if ( $type == ResourceLoaderModule::TYPE_COMBINED ) { return min( array_values( $this->mAllowedModules ) ); } else { - return isset( $this->mAllowedModules[$type] ) - ? $this->mAllowedModules[$type] - : ResourceLoaderModule::ORIGIN_ALL; + return $this->mAllowedModules[$type] ?? ResourceLoaderModule::ORIGIN_ALL; } } @@ -3904,7 +3900,7 @@ class OutputPage extends ContextSource { */ public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) { $themes = ResourceLoaderOOUIModule::getSkinThemeMap(); - $theme = isset( $themes[$skinName] ) ? $themes[$skinName] : $themes['default']; + $theme = $themes[$skinName] ?? $themes['default']; // For example, 'OOUI\WikimediaUITheme'. $themeClass = "OOUI\\{$theme}Theme"; OOUI\Theme::setSingleton( new $themeClass() ); diff --git a/includes/PrefixSearch.php b/includes/PrefixSearch.php index 62ee5c650d..5127158e69 100644 --- a/includes/PrefixSearch.php +++ b/includes/PrefixSearch.php @@ -211,7 +211,7 @@ abstract class PrefixSearch { $searchParts = explode( '/', $search, 2 ); $searchKey = $searchParts[0]; - $subpageSearch = isset( $searchParts[1] ) ? $searchParts[1] : null; + $subpageSearch = $searchParts[1] ?? null; // Handle subpage search separately. if ( $subpageSearch !== null ) { diff --git a/includes/Revision.php b/includes/Revision.php index 548ef8d720..213abbef90 100644 --- a/includes/Revision.php +++ b/includes/Revision.php @@ -581,11 +581,11 @@ class Revision implements IDBAccessObject { return $row['title']; } - $pageId = isset( $row['page'] ) ? $row['page'] : 0; - $revId = isset( $row['id'] ) ? $row['id'] : 0; + $pageId = $row['page'] ?? 0; + $revId = $row['id'] ?? 0; } else { - $pageId = isset( $row->rev_page ) ? $row->rev_page : 0; - $revId = isset( $row->rev_id ) ? $row->rev_id : 0; + $pageId = $row->rev_page ?? 0; + $revId = $row->rev_id ?? 0; } try { diff --git a/includes/ServiceWiring.php b/includes/ServiceWiring.php index ee92cbfecf..ace64ab928 100644 --- a/includes/ServiceWiring.php +++ b/includes/ServiceWiring.php @@ -415,9 +415,7 @@ return [ foreach ( $config['paths'] as $prefix => $serviceConfig ) { $class = $serviceConfig['class']; // Merge in the global defaults - $constructArg = isset( $serviceConfig['options'] ) - ? $serviceConfig['options'] - : []; + $constructArg = $serviceConfig['options'] ?? []; $constructArg += $config['global']; // Make the VRS service available at the mount point $vrsClient->mount( $prefix, [ 'class' => $class, 'config' => $constructArg ] ); diff --git a/includes/Storage/RevisionStore.php b/includes/Storage/RevisionStore.php index 5b3daf45a4..36af6cd8c2 100644 --- a/includes/Storage/RevisionStore.php +++ b/includes/Storage/RevisionStore.php @@ -1117,9 +1117,9 @@ class RevisionStore try { $user = User::newFromAnyId( - isset( $row->ar_user ) ? $row->ar_user : null, - isset( $row->ar_user_text ) ? $row->ar_user_text : null, - isset( $row->ar_actor ) ? $row->ar_actor : null + $row->ar_user ?? null, + $row->ar_user_text ?? null, + $row->ar_actor ?? null ); } catch ( InvalidArgumentException $ex ) { wfWarn( __METHOD__ . ': ' . $ex->getMessage() ); @@ -1153,8 +1153,8 @@ class RevisionStore Assert::parameterType( 'object', $row, '$row' ); if ( !$title ) { - $pageId = isset( $row->rev_page ) ? $row->rev_page : 0; // XXX: also check page_id? - $revId = isset( $row->rev_id ) ? $row->rev_id : 0; + $pageId = $row->rev_page ?? 0; // XXX: also check page_id? + $revId = $row->rev_id ?? 0; $title = $this->getTitle( $pageId, $revId, $queryFlags ); } @@ -1168,9 +1168,9 @@ class RevisionStore try { $user = User::newFromAnyId( - isset( $row->rev_user ) ? $row->rev_user : null, - isset( $row->rev_user_text ) ? $row->rev_user_text : null, - isset( $row->rev_actor ) ? $row->rev_actor : null + $row->rev_user ?? null, + $row->rev_user_text ?? null, + $row->rev_actor ?? null ); } catch ( InvalidArgumentException $ex ) { wfWarn( __METHOD__ . ': ' . $ex->getMessage() ); @@ -1230,8 +1230,8 @@ class RevisionStore } if ( !$title ) { - $pageId = isset( $fields['page'] ) ? $fields['page'] : 0; - $revId = isset( $fields['id'] ) ? $fields['id'] : 0; + $pageId = $fields['page'] ?? 0; + $revId = $fields['id'] ?? 0; $title = $this->getTitle( $pageId, $revId, $queryFlags ); } @@ -1258,7 +1258,7 @@ class RevisionStore isset( $fields['comment'] ) && !( $fields['comment'] instanceof CommentStoreComment ) ) { - $commentData = isset( $fields['comment_data'] ) ? $fields['comment_data'] : null; + $commentData = $fields['comment_data'] ?? null; if ( $fields['comment'] instanceof Message ) { $fields['comment'] = CommentStoreComment::newUnsavedComment( @@ -1299,9 +1299,9 @@ class RevisionStore } else { try { $user = User::newFromAnyId( - isset( $fields['user'] ) ? $fields['user'] : null, - isset( $fields['user_text'] ) ? $fields['user_text'] : null, - isset( $fields['actor'] ) ? $fields['actor'] : null + $fields['user'] ?? null, + $fields['user_text'] ?? null, + $fields['actor'] ?? null ); } catch ( InvalidArgumentException $ex ) { $user = null; diff --git a/includes/Title.php b/includes/Title.php index 78d9850f07..9711749d33 100644 --- a/includes/Title.php +++ b/includes/Title.php @@ -3086,9 +3086,7 @@ class Title implements LinkTarget { if ( !$this->mRestrictionsLoaded ) { $this->loadRestrictions(); } - return isset( $this->mRestrictions[$action] ) - ? $this->mRestrictions[$action] - : []; + return $this->mRestrictions[$action] ?? []; } /** @@ -3116,7 +3114,7 @@ class Title implements LinkTarget { if ( !$this->mRestrictionsLoaded ) { $this->loadRestrictions(); } - return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false; + return $this->mRestrictionsExpiry[$action] ?? false; } /** diff --git a/includes/WebRequest.php b/includes/WebRequest.php index e0b8de7076..b499d86d39 100644 --- a/includes/WebRequest.php +++ b/includes/WebRequest.php @@ -129,7 +129,7 @@ class WebRequest { $a = parse_url( $url ); Wikimedia\restoreWarnings(); if ( $a ) { - $path = isset( $a['path'] ) ? $a['path'] : ''; + $path = $a['path'] ?? ''; global $wgScript; if ( $path == $wgScript && $want !== 'all' ) { @@ -275,8 +275,7 @@ class WebRequest { // This method is called from various error handlers and should be kept simple. if ( !self::$reqId ) { - self::$reqId = isset( $_SERVER['UNIQUE_ID'] ) - ? $_SERVER['UNIQUE_ID'] : wfRandomString( 24 ); + self::$reqId = $_SERVER['UNIQUE_ID'] ?? wfRandomString( 24 ); } return self::$reqId; @@ -458,7 +457,7 @@ class WebRequest { * @return mixed Old value if one was present, null otherwise */ public function setVal( $key, $value ) { - $ret = isset( $this->data[$key] ) ? $this->data[$key] : null; + $ret = $this->data[$key] ?? null; $this->data[$key] = $value; return $ret; } @@ -714,7 +713,7 @@ class WebRequest { * @return string */ public function getMethod() { - return isset( $_SERVER['REQUEST_METHOD'] ) ? $_SERVER['REQUEST_METHOD'] : 'GET'; + return $_SERVER['REQUEST_METHOD'] ?? 'GET'; } /** diff --git a/includes/WikiMap.php b/includes/WikiMap.php index 8bb37b5c88..90ebc4bc41 100644 --- a/includes/WikiMap.php +++ b/includes/WikiMap.php @@ -104,7 +104,7 @@ class WikiMap { $path .= '?' . $urlParts['query']; } - $canonicalServer = isset( $urlParts['scheme'] ) ? $urlParts['scheme'] : 'http'; + $canonicalServer = $urlParts['scheme'] ?? 'http'; $canonicalServer .= '://' . $urlParts['host']; return new WikiReference( $canonicalServer, $path ); diff --git a/includes/actions/HistoryAction.php b/includes/actions/HistoryAction.php index f7ac21b76e..ad26256daa 100644 --- a/includes/actions/HistoryAction.php +++ b/includes/actions/HistoryAction.php @@ -711,9 +711,7 @@ class HistoryPager extends ReverseChronologicalPager { # Sometimes rev_len isn't populated if ( $rev->getSize() !== null ) { # Size is always public data - $prevSize = isset( $this->parentLens[$row->rev_parent_id] ) - ? $this->parentLens[$row->rev_parent_id] - : 0; + $prevSize = $this->parentLens[$row->rev_parent_id] ?? 0; $sDiff = ChangesList::showCharacterDifference( $prevSize, $rev->getSize() ); $fSize = Linker::formatRevisionSize( $rev->getSize() ); $s .= ' . . ' . "$fSize $sDiff"; diff --git a/includes/api/ApiAuthManagerHelper.php b/includes/api/ApiAuthManagerHelper.php index d6b9f7612f..e37b4d481d 100644 --- a/includes/api/ApiAuthManagerHelper.php +++ b/includes/api/ApiAuthManagerHelper.php @@ -48,7 +48,7 @@ class ApiAuthManagerHelper { $this->module = $module; $params = $module->extractRequestParams(); - $this->messageFormat = isset( $params['messageformat'] ) ? $params['messageformat'] : 'wikitext'; + $this->messageFormat = $params['messageformat'] ?? 'wikitext'; } /** diff --git a/includes/api/ApiBase.php b/includes/api/ApiBase.php index 02a635a712..8a99e6a97f 100644 --- a/includes/api/ApiBase.php +++ b/includes/api/ApiBase.php @@ -1156,36 +1156,16 @@ abstract class ApiBase extends ContextSource { ]; } - $default = isset( $paramSettings[self::PARAM_DFLT] ) - ? $paramSettings[self::PARAM_DFLT] - : null; - $multi = isset( $paramSettings[self::PARAM_ISMULTI] ) - ? $paramSettings[self::PARAM_ISMULTI] - : false; - $multiLimit1 = isset( $paramSettings[self::PARAM_ISMULTI_LIMIT1] ) - ? $paramSettings[self::PARAM_ISMULTI_LIMIT1] - : null; - $multiLimit2 = isset( $paramSettings[self::PARAM_ISMULTI_LIMIT2] ) - ? $paramSettings[self::PARAM_ISMULTI_LIMIT2] - : null; - $type = isset( $paramSettings[self::PARAM_TYPE] ) - ? $paramSettings[self::PARAM_TYPE] - : null; - $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] ) - ? $paramSettings[self::PARAM_ALLOW_DUPLICATES] - : false; - $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] ) - ? $paramSettings[self::PARAM_DEPRECATED] - : false; - $deprecatedValues = isset( $paramSettings[self::PARAM_DEPRECATED_VALUES] ) - ? $paramSettings[self::PARAM_DEPRECATED_VALUES] - : []; - $required = isset( $paramSettings[self::PARAM_REQUIRED] ) - ? $paramSettings[self::PARAM_REQUIRED] - : false; - $allowAll = isset( $paramSettings[self::PARAM_ALL] ) - ? $paramSettings[self::PARAM_ALL] - : false; + $default = $paramSettings[self::PARAM_DFLT] ?? null; + $multi = $paramSettings[self::PARAM_ISMULTI] ?? false; + $multiLimit1 = $paramSettings[self::PARAM_ISMULTI_LIMIT1] ?? null; + $multiLimit2 = $paramSettings[self::PARAM_ISMULTI_LIMIT2] ?? null; + $type = $paramSettings[self::PARAM_TYPE] ?? null; + $dupes = $paramSettings[self::PARAM_ALLOW_DUPLICATES] ?? false; + $deprecated = $paramSettings[self::PARAM_DEPRECATED] ?? false; + $deprecatedValues = $paramSettings[self::PARAM_DEPRECATED_VALUES] ?? []; + $required = $paramSettings[self::PARAM_REQUIRED] ?? false; + $allowAll = $paramSettings[self::PARAM_ALL] ?? false; // When type is not given, and no choices, the type is the same as $default if ( !isset( $type ) ) { @@ -1313,10 +1293,9 @@ abstract class ApiBase extends ContextSource { } break; case 'integer': // Force everything using intval() and optionally validate limits - $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null; - $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null; - $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] ) - ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false; + $min = $paramSettings[self::PARAM_MIN] ?? null; + $max = $paramSettings[self::PARAM_MAX] ?? null; + $enforceLimits = $paramSettings[self::PARAM_RANGE_ENFORCE] ?? false; if ( is_array( $value ) ) { $value = array_map( 'intval', $value ); @@ -1348,7 +1327,7 @@ abstract class ApiBase extends ContextSource { if ( $multi ) { self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" ); } - $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0; + $min = $paramSettings[self::PARAM_MIN] ?? 0; if ( $value == 'max' ) { $value = $this->getMain()->canApiHighLimits() ? $paramSettings[self::PARAM_MAX2] @@ -2335,7 +2314,7 @@ abstract class ApiBase extends ContextSource { 'api-help-param-token', $this->needsToken(), ], - ] + ( isset( $params['token'] ) ? $params['token'] : [] ); + ] + ( $params['token'] ?? [] ); } // Avoid PHP 7.1 warning of passing $this by reference @@ -2375,7 +2354,7 @@ abstract class ApiBase extends ContextSource { $settings = []; } - $d = isset( $desc[$param] ) ? $desc[$param] : ''; + $d = $desc[$param] ?? ''; if ( is_array( $d ) ) { // Special handling for prop parameters $d = array_map( function ( $line ) { @@ -2457,9 +2436,7 @@ abstract class ApiBase extends ContextSource { } $valueMsgs = $settings[self::PARAM_HELP_MSG_PER_VALUE]; - $deprecatedValues = isset( $settings[self::PARAM_DEPRECATED_VALUES] ) - ? $settings[self::PARAM_DEPRECATED_VALUES] - : []; + $deprecatedValues = $settings[self::PARAM_DEPRECATED_VALUES] ?? []; foreach ( $settings[self::PARAM_TYPE] as $value ) { if ( isset( $valueMsgs[$value] ) ) { @@ -2811,7 +2788,7 @@ abstract class ApiBase extends ContextSource { if ( !$msg instanceof IApiMessage ) { $key = $msg->getKey(); $params = $msg->getParams(); - array_unshift( $params, isset( self::$messageMap[$key] ) ? self::$messageMap[$key] : $key ); + array_unshift( $params, self::$messageMap[$key] ?? $key ); $msg = ApiMessage::create( $params ); } diff --git a/includes/api/ApiCSPReport.php b/includes/api/ApiCSPReport.php index 82a7cce44b..6271128171 100644 --- a/includes/api/ApiCSPReport.php +++ b/includes/api/ApiCSPReport.php @@ -176,8 +176,8 @@ class ApiCSPReport extends ApiBase { $flagText = '[' . implode( ', ', $flags ) . ']'; } - $blockedFile = isset( $report['blocked-uri'] ) ? $report['blocked-uri'] : 'n/a'; - $page = isset( $report['document-uri'] ) ? $report['document-uri'] : 'n/a'; + $blockedFile = $report['blocked-uri'] ?? 'n/a'; + $page = $report['document-uri'] ?? 'n/a'; $line = isset( $report['line-number'] ) ? ':' . $report['line-number'] : ''; $warningText = $flagText . ' Received CSP report: <' . $blockedFile . diff --git a/includes/api/ApiErrorFormatter.php b/includes/api/ApiErrorFormatter.php index c637752dfb..af23f95f5c 100644 --- a/includes/api/ApiErrorFormatter.php +++ b/includes/api/ApiErrorFormatter.php @@ -203,7 +203,7 @@ class ApiErrorFormatter { public function formatException( $exception, array $options = [] ) { return $this->formatMessage( $this->getMessageFromException( $exception, $options ), - isset( $options['format'] ) ? $options['format'] : null + $options['format'] ?? null ); } diff --git a/includes/api/ApiFeedWatchlist.php b/includes/api/ApiFeedWatchlist.php index 393e536227..c21ac12e82 100644 --- a/includes/api/ApiFeedWatchlist.php +++ b/includes/api/ApiFeedWatchlist.php @@ -144,7 +144,7 @@ class ApiFeedWatchlist extends ApiBase { ' [' . $this->getConfig()->get( 'LanguageCode' ) . ']'; $feedUrl = SpecialPage::getTitleFor( 'Watchlist' )->getFullURL(); - $feedFormat = isset( $params['feedformat'] ) ? $params['feedformat'] : 'rss'; + $feedFormat = $params['feedformat'] ?? 'rss'; $msg = wfMessage( 'watchlist' )->inContentLanguage()->escaped(); $feed = new $feedClasses[$feedFormat] ( $feedTitle, $msg, $feedUrl ); @@ -201,7 +201,7 @@ class ApiFeedWatchlist extends ApiBase { } else { $titleUrl = $title->getFullURL( $curidParam ); } - $comment = isset( $info['comment'] ) ? $info['comment'] : null; + $comment = $info['comment'] ?? null; // Create an anchor to section. // The anchor won't work for sections that have dupes on page diff --git a/includes/api/ApiFormatXml.php b/includes/api/ApiFormatXml.php index cc1bd820f0..73e9e5875c 100644 --- a/includes/api/ApiFormatXml.php +++ b/includes/api/ApiFormatXml.php @@ -104,26 +104,18 @@ class ApiFormatXml extends ApiFormatBase { $value = (array)$value; } if ( is_array( $value ) ) { - $contentKey = isset( $value[ApiResult::META_CONTENT] ) - ? $value[ApiResult::META_CONTENT] - : '*'; - $subelementKeys = isset( $value[ApiResult::META_SUBELEMENTS] ) - ? $value[ApiResult::META_SUBELEMENTS] - : []; + $contentKey = $value[ApiResult::META_CONTENT] ?? '*'; + $subelementKeys = $value[ApiResult::META_SUBELEMENTS] ?? []; if ( isset( $value[ApiResult::META_BC_SUBELEMENTS] ) ) { $subelementKeys = array_merge( $subelementKeys, $value[ApiResult::META_BC_SUBELEMENTS] ); } - $preserveKeys = isset( $value[ApiResult::META_PRESERVE_KEYS] ) - ? $value[ApiResult::META_PRESERVE_KEYS] - : []; + $preserveKeys = $value[ApiResult::META_PRESERVE_KEYS] ?? []; $indexedTagName = isset( $value[ApiResult::META_INDEXED_TAG_NAME] ) ? self::mangleName( $value[ApiResult::META_INDEXED_TAG_NAME], $preserveKeys ) : '_v'; - $bcBools = isset( $value[ApiResult::META_BC_BOOLS] ) - ? $value[ApiResult::META_BC_BOOLS] - : []; + $bcBools = $value[ApiResult::META_BC_BOOLS] ?? []; $indexSubelements = isset( $value[ApiResult::META_TYPE] ) ? $value[ApiResult::META_TYPE] !== 'array' : false; diff --git a/includes/api/ApiHelp.php b/includes/api/ApiHelp.php index bccb3385c2..8b0204c983 100644 --- a/includes/api/ApiHelp.php +++ b/includes/api/ApiHelp.php @@ -149,7 +149,7 @@ class ApiHelp extends ApiBase { } $out->addHTML( $html ); - $helptitle = isset( $options['helptitle'] ) ? $options['helptitle'] : null; + $helptitle = $options['helptitle'] ?? null; $html = self::fixHelpLinks( $out->getHTML(), $helptitle, $haveModules ); $out->clearHTML(); $out->addHTML( $html ); @@ -482,9 +482,7 @@ class ApiHelp extends ApiBase { // Type documentation if ( !isset( $settings[ApiBase::PARAM_TYPE] ) ) { - $dflt = isset( $settings[ApiBase::PARAM_DFLT] ) - ? $settings[ApiBase::PARAM_DFLT] - : null; + $dflt = $settings[ApiBase::PARAM_DFLT] ?? null; if ( is_bool( $dflt ) ) { $settings[ApiBase::PARAM_TYPE] = 'boolean'; } elseif ( is_string( $dflt ) || is_null( $dflt ) ) { @@ -503,12 +501,8 @@ class ApiHelp extends ApiBase { if ( is_array( $type ) ) { $count = count( $type ); - $deprecatedValues = isset( $settings[ApiBase::PARAM_DEPRECATED_VALUES] ) - ? $settings[ApiBase::PARAM_DEPRECATED_VALUES] - : []; - $links = isset( $settings[ApiBase::PARAM_VALUE_LINKS] ) - ? $settings[ApiBase::PARAM_VALUE_LINKS] - : []; + $deprecatedValues = $settings[ApiBase::PARAM_DEPRECATED_VALUES] ?? []; + $links = $settings[ApiBase::PARAM_VALUE_LINKS] ?? []; $values = array_map( function ( $v ) use ( $links, $deprecatedValues ) { $attr = []; if ( $v !== '' ) { @@ -707,9 +701,7 @@ class ApiHelp extends ApiBase { $info[] = implode( ' ', $extra ); } - $allowAll = isset( $settings[ApiBase::PARAM_ALL] ) - ? $settings[ApiBase::PARAM_ALL] - : false; + $allowAll = $settings[ApiBase::PARAM_ALL] ?? false; if ( $allowAll || $settings[ApiBase::PARAM_TYPE] === 'namespace' ) { if ( $settings[ApiBase::PARAM_TYPE] === 'namespace' ) { $allSpecifier = ApiBase::ALL_DEFAULT_STRING; @@ -733,9 +725,7 @@ class ApiHelp extends ApiBase { } // Add default - $default = isset( $settings[ApiBase::PARAM_DFLT] ) - ? $settings[ApiBase::PARAM_DFLT] - : null; + $default = $settings[ApiBase::PARAM_DFLT] ?? null; if ( $default === '' ) { $info[] = $context->msg( 'api-help-param-default-empty' ) ->parse(); diff --git a/includes/api/ApiModuleManager.php b/includes/api/ApiModuleManager.php index e02c862778..fec55aa6cd 100644 --- a/includes/api/ApiModuleManager.php +++ b/includes/api/ApiModuleManager.php @@ -96,7 +96,7 @@ class ApiModuleManager extends ContextSource { foreach ( $modules as $name => $moduleSpec ) { if ( is_array( $moduleSpec ) ) { $class = $moduleSpec['class']; - $factory = ( isset( $moduleSpec['factory'] ) ? $moduleSpec['factory'] : null ); + $factory = ( $moduleSpec['factory'] ?? null ); } else { $class = $moduleSpec; $factory = null; diff --git a/includes/api/ApiOptions.php b/includes/api/ApiOptions.php index 4b76906030..f30b44c4aa 100644 --- a/includes/api/ApiOptions.php +++ b/includes/api/ApiOptions.php @@ -65,11 +65,11 @@ class ApiOptions extends ApiBase { if ( $params['change'] ) { foreach ( $params['change'] as $entry ) { $array = explode( '=', $entry, 2 ); - $changes[$array[0]] = isset( $array[1] ) ? $array[1] : null; + $changes[$array[0]] = $array[1] ?? null; } } if ( isset( $params['optionname'] ) ) { - $newValue = isset( $params['optionvalue'] ) ? $params['optionvalue'] : null; + $newValue = $params['optionvalue'] ?? null; $changes[$params['optionname']] = $newValue; } if ( !$changed && !count( $changes ) ) { diff --git a/includes/api/ApiParamInfo.php b/includes/api/ApiParamInfo.php index b8a32ae430..c81cf7ee13 100644 --- a/includes/api/ApiParamInfo.php +++ b/includes/api/ApiParamInfo.php @@ -339,9 +339,7 @@ class ApiParamInfo extends ApiBase { } if ( !isset( $settings[ApiBase::PARAM_TYPE] ) ) { - $dflt = isset( $settings[ApiBase::PARAM_DFLT] ) - ? $settings[ApiBase::PARAM_DFLT] - : null; + $dflt = $settings[ApiBase::PARAM_DFLT] ?? null; if ( is_bool( $dflt ) ) { $settings[ApiBase::PARAM_TYPE] = 'boolean'; } elseif ( is_string( $dflt ) || is_null( $dflt ) ) { @@ -445,9 +443,7 @@ class ApiParamInfo extends ApiBase { $allowAll = true; $allSpecifier = ApiBase::ALL_DEFAULT_STRING; } else { - $allowAll = isset( $settings[ApiBase::PARAM_ALL] ) - ? $settings[ApiBase::PARAM_ALL] - : false; + $allowAll = $settings[ApiBase::PARAM_ALL] ?? false; $allSpecifier = ( is_string( $allowAll ) ? $allowAll : ApiBase::ALL_DEFAULT_STRING ); } if ( $allowAll && $item['multi'] && diff --git a/includes/api/ApiQueryBacklinksprop.php b/includes/api/ApiQueryBacklinksprop.php index fb90e25c38..b338ed6774 100644 --- a/includes/api/ApiQueryBacklinksprop.php +++ b/includes/api/ApiQueryBacklinksprop.php @@ -419,7 +419,7 @@ class ApiQueryBacklinksprop extends ApiQueryGeneratorBase { $settings = self::$settings[$this->getModuleName()]; $name = $this->getModuleName(); $path = $this->getModulePath(); - $title = isset( $settings['exampletitle'] ) ? $settings['exampletitle'] : 'Main Page'; + $title = $settings['exampletitle'] ?? 'Main Page'; $etitle = rawurlencode( $title ); return [ diff --git a/includes/api/ApiQueryExternalLinks.php b/includes/api/ApiQueryExternalLinks.php index fd196aab09..6c219d4a91 100644 --- a/includes/api/ApiQueryExternalLinks.php +++ b/includes/api/ApiQueryExternalLinks.php @@ -66,7 +66,7 @@ class ApiQueryExternalLinks extends ApiQueryBase { } $this->addOption( 'LIMIT', $params['limit'] + 1 ); - $offset = isset( $params['offset'] ) ? $params['offset'] : 0; + $offset = $params['offset'] ?? 0; if ( $offset ) { $this->addOption( 'OFFSET', $params['offset'] ); } diff --git a/includes/api/ApiQuerySiteinfo.php b/includes/api/ApiQuerySiteinfo.php index 3f2d510343..4b408fc481 100644 --- a/includes/api/ApiQuerySiteinfo.php +++ b/includes/api/ApiQuerySiteinfo.php @@ -54,7 +54,7 @@ class ApiQuerySiteinfo extends ApiQueryBase { $fit = $this->appendMagicWords( $p ); break; case 'interwikimap': - $filteriw = isset( $params['filteriw'] ) ? $params['filteriw'] : false; + $filteriw = $params['filteriw'] ?? false; $fit = $this->appendInterwikiMap( $p, $filteriw ); break; case 'dbrepllag': @@ -387,7 +387,7 @@ class ApiQuerySiteinfo extends ApiQueryBase { } $params = $this->extractRequestParams(); - $langCode = isset( $params['inlanguagecode'] ) ? $params['inlanguagecode'] : ''; + $langCode = $params['inlanguagecode'] ?? ''; $langNames = Language::fetchLanguageNames( $langCode ); $getPrefixes = MediaWikiServices::getInstance()->getInterwikiLookup()->getAllPrefixes( $local ); @@ -629,7 +629,7 @@ class ApiQuerySiteinfo extends ApiQueryBase { } if ( SpecialVersion::getExtLicenseFileName( $extensionPath ) ) { - $ret['license-name'] = isset( $ext['license-name'] ) ? $ext['license-name'] : ''; + $ret['license-name'] = $ext['license-name'] ?? ''; $ret['license'] = SpecialPage::getTitleFor( 'Version', "License/{$ext['name']}" @@ -699,7 +699,7 @@ class ApiQuerySiteinfo extends ApiQueryBase { public function appendLanguages( $property ) { $params = $this->extractRequestParams(); - $langCode = isset( $params['inlanguagecode'] ) ? $params['inlanguagecode'] : ''; + $langCode = $params['inlanguagecode'] ?? ''; $langNames = Language::fetchLanguageNames( $langCode ); $data = []; diff --git a/includes/api/ApiQueryUserContribs.php b/includes/api/ApiQueryUserContribs.php index f1c4f9407a..420d138df7 100644 --- a/includes/api/ApiQueryUserContribs.php +++ b/includes/api/ApiQueryUserContribs.php @@ -691,9 +691,7 @@ class ApiQueryUserContribs extends ApiQueryBase { && !is_null( $row->rev_len ) && !is_null( $row->rev_parent_id ) ) { - $parentLen = isset( $this->parentLens[$row->rev_parent_id] ) - ? $this->parentLens[$row->rev_parent_id] - : 0; + $parentLen = $this->parentLens[$row->rev_parent_id] ?? 0; $vals['sizediff'] = intval( $row->rev_len - $parentLen ); } diff --git a/includes/api/ApiResult.php b/includes/api/ApiResult.php index 1afacafc3b..df7183030e 100644 --- a/includes/api/ApiResult.php +++ b/includes/api/ApiResult.php @@ -804,11 +804,11 @@ class ApiResult implements ApiSerializable { * @return array|object */ protected static function applyTransformations( array $dataIn, array $transforms ) { - $strip = isset( $transforms['Strip'] ) ? $transforms['Strip'] : 'none'; + $strip = $transforms['Strip'] ?? 'none'; if ( $strip === 'base' ) { $transforms['Strip'] = 'none'; } - $transformTypes = isset( $transforms['Types'] ) ? $transforms['Types'] : null; + $transformTypes = $transforms['Types'] ?? null; if ( $transformTypes !== null && !is_array( $transformTypes ) ) { throw new InvalidArgumentException( __METHOD__ . ':Value for "Types" must be an array' ); } @@ -954,9 +954,7 @@ class ApiResult implements ApiSerializable { case 'kvp': case 'BCkvp': - $key = isset( $metadata[self::META_KVP_KEY_NAME] ) - ? $metadata[self::META_KVP_KEY_NAME] - : $transformTypes['ArmorKVP']; + $key = $metadata[self::META_KVP_KEY_NAME] ?? $transformTypes['ArmorKVP']; $valKey = isset( $transforms['BC'] ) ? '*' : 'value'; $assocAsObject = !empty( $transformTypes['AssocAsObject'] ); $merge = !empty( $metadata[self::META_KVP_MERGE] ); diff --git a/includes/api/ApiRsd.php b/includes/api/ApiRsd.php index f20d1c6c8b..71bab365af 100644 --- a/includes/api/ApiRsd.php +++ b/includes/api/ApiRsd.php @@ -120,7 +120,7 @@ class ApiRsd extends ApiBase { 'name' => $name, 'preferred' => wfBoolToStr( $name == 'MediaWiki' ), 'apiLink' => $info['apiLink'], - 'blogID' => isset( $info['blogID'] ) ? $info['blogID'] : '', + 'blogID' => $info['blogID'] ?? '', ]; $settings = []; if ( isset( $info['docs'] ) ) { diff --git a/includes/api/ApiUndelete.php b/includes/api/ApiUndelete.php index ee5c3a2f54..840ef1bc83 100644 --- a/includes/api/ApiUndelete.php +++ b/includes/api/ApiUndelete.php @@ -65,7 +65,7 @@ class ApiUndelete extends ApiBase { $pa = new PageArchive( $titleObj, $this->getConfig() ); $retval = $pa->undelete( - ( isset( $params['timestamps'] ) ? $params['timestamps'] : [] ), + ( $params['timestamps'] ?? [] ), $params['reason'], $params['fileids'], false, diff --git a/includes/api/ApiUpload.php b/includes/api/ApiUpload.php index 93e432b951..2c5b583f3b 100644 --- a/includes/api/ApiUpload.php +++ b/includes/api/ApiUpload.php @@ -682,9 +682,7 @@ class ApiUpload extends ApiBase { $warning = $warnings['exists']; unset( $warnings['exists'] ); /** @var LocalFile $localFile */ - $localFile = isset( $warning['normalizedFile'] ) - ? $warning['normalizedFile'] - : $warning['file']; + $localFile = $warning['normalizedFile'] ?? $warning['file']; $warnings[$warning['warning']] = $localFile->getName(); } diff --git a/includes/api/ApiUserrights.php b/includes/api/ApiUserrights.php index 47f3bc5a4d..e251fe6943 100644 --- a/includes/api/ApiUserrights.php +++ b/includes/api/ApiUserrights.php @@ -134,7 +134,7 @@ class ApiUserrights extends ApiBase { $this->requireOnlyOneParameter( $params, 'user', 'userid' ); - $user = isset( $params['user'] ) ? $params['user'] : '#' . $params['userid']; + $user = $params['user'] ?? '#' . $params['userid']; $form = $this->getUserRightsPage(); $form->setContext( $this->getContext() ); diff --git a/includes/api/SearchApi.php b/includes/api/SearchApi.php index f7c6471e7c..40d477880f 100644 --- a/includes/api/SearchApi.php +++ b/includes/api/SearchApi.php @@ -150,7 +150,7 @@ trait SearchApi { */ public function buildSearchEngine( array $params = null ) { if ( $params != null ) { - $type = isset( $params['backend'] ) ? $params['backend'] : null; + $type = $params['backend'] ?? null; if ( $type === self::$BACKEND_NULL_PARAM ) { $type = null; } diff --git a/includes/auth/AuthManager.php b/includes/auth/AuthManager.php index 258e5203f1..2adc00efae 100644 --- a/includes/auth/AuthManager.php +++ b/includes/auth/AuthManager.php @@ -1675,7 +1675,7 @@ class AuthManager implements LoggerAwareInterface { } // Checks passed, create the user... - $from = isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : 'CLI'; + $from = $_SERVER['REQUEST_URI'] ?? 'CLI'; $this->logger->info( __METHOD__ . ': creating new user ({username}) - from: {from}', [ 'username' => $username, 'from' => $from, diff --git a/includes/auth/ResetPasswordSecondaryAuthenticationProvider.php b/includes/auth/ResetPasswordSecondaryAuthenticationProvider.php index 45ac3aa0b5..c831fc8c44 100644 --- a/includes/auth/ResetPasswordSecondaryAuthenticationProvider.php +++ b/includes/auth/ResetPasswordSecondaryAuthenticationProvider.php @@ -96,7 +96,7 @@ class ResetPasswordSecondaryAuthenticationProvider extends AbstractSecondaryAuth } } - $needReq = isset( $data->req ) ? $data->req : new PasswordAuthenticationRequest(); + $needReq = $data->req ?? new PasswordAuthenticationRequest(); if ( !$needReq->action ) { $needReq->action = AuthManager::ACTION_CHANGE; } diff --git a/includes/auth/ThrottlePreAuthenticationProvider.php b/includes/auth/ThrottlePreAuthenticationProvider.php index ae0bc6bb77..83d67eabf6 100644 --- a/includes/auth/ThrottlePreAuthenticationProvider.php +++ b/includes/auth/ThrottlePreAuthenticationProvider.php @@ -58,8 +58,7 @@ class ThrottlePreAuthenticationProvider extends AbstractPreAuthenticationProvide public function __construct( $params = [] ) { $this->throttleSettings = array_intersect_key( $params, [ 'accountCreationThrottle' => true, 'passwordAttemptThrottle' => true ] ); - $this->cache = isset( $params['cache'] ) ? $params['cache'] : - \ObjectCache::getLocalClusterInstance(); + $this->cache = $params['cache'] ?? \ObjectCache::getLocalClusterInstance(); } public function setConfig( Config $config ) { diff --git a/includes/cache/GenderCache.php b/includes/cache/GenderCache.php index 099a986f7b..1ec39a54d6 100644 --- a/includes/cache/GenderCache.php +++ b/includes/cache/GenderCache.php @@ -85,7 +85,7 @@ class GenderCache { /* Undefined if there is a valid username which for some reason doesn't * exist in the database. */ - return isset( $this->cache[$username] ) ? $this->cache[$username] : $this->getDefault(); + return $this->cache[$username] ?? $this->getDefault(); } /** diff --git a/includes/cache/MessageCache.php b/includes/cache/MessageCache.php index 71fcd8bde5..23a5da5f80 100644 --- a/includes/cache/MessageCache.php +++ b/includes/cache/MessageCache.php @@ -727,7 +727,7 @@ class MessageCache { $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ), [ 'hash' => $cache['HASH'], - 'latest' => isset( $cache['LATEST'] ) ? $cache['LATEST'] : 0 + 'latest' => $cache['LATEST'] ?? 0 ], WANObjectCache::TTL_INDEFINITE ); diff --git a/includes/cache/UserCache.php b/includes/cache/UserCache.php index cb6857121e..2828b9a71f 100644 --- a/includes/cache/UserCache.php +++ b/includes/cache/UserCache.php @@ -56,9 +56,7 @@ class UserCache { $this->doQuery( [ $userId ] ); // cache miss } - return isset( $this->cache[$userId][$prop] ) - ? $this->cache[$userId][$prop] - : false; // user does not exist? + return $this->cache[$userId][$prop] ?? false; // user does not exist? } /** diff --git a/includes/changes/ChangesList.php b/includes/changes/ChangesList.php index ac029a2bb3..d7e9052112 100644 --- a/includes/changes/ChangesList.php +++ b/includes/changes/ChangesList.php @@ -236,7 +236,7 @@ class ChangesList extends ContextSource { $flagInfos[$key]['letter'] = $value['letter']; $flagInfos[$key]['title'] = $value['title']; // Allow customized class name, fall back to flag name - $flagInfos[$key]['class'] = isset( $value['class'] ) ? $value['class'] : $key; + $flagInfos[$key]['class'] = $value['class'] ?? $key; } } @@ -646,7 +646,7 @@ class ChangesList extends ContextSource { 'id' => $rc->mAttribs['rc_this_oldid'], 'user' => $rc->mAttribs['rc_user'], 'user_text' => $rc->mAttribs['rc_user_text'], - 'actor' => isset( $rc->mAttribs['rc_actor'] ) ? $rc->mAttribs['rc_actor'] : null, + 'actor' => $rc->mAttribs['rc_actor'] ?? null, 'deleted' => $rc->mAttribs['rc_deleted'] ] ); $s .= ' ' . Linker::generateRollback( $rev, $this->getContext() ); diff --git a/includes/changes/ChangesListFilterGroup.php b/includes/changes/ChangesListFilterGroup.php index 79e8e33e8a..9d3053762d 100644 --- a/includes/changes/ChangesListFilterGroup.php +++ b/includes/changes/ChangesListFilterGroup.php @@ -322,7 +322,7 @@ abstract class ChangesListFilterGroup { * @return ChangesListFilter|null Specified filter, or null if it is not registered */ public function getFilter( $name ) { - return isset( $this->filters[$name] ) ? $this->filters[$name] : null; + return $this->filters[$name] ?? null; } /** diff --git a/includes/changes/EnhancedChangesList.php b/includes/changes/EnhancedChangesList.php index 6c7666fba5..bad5c5a1e5 100644 --- a/includes/changes/EnhancedChangesList.php +++ b/includes/changes/EnhancedChangesList.php @@ -203,8 +203,7 @@ class EnhancedChangesList extends ChangesList { # Default values for RC flags $collectedRcFlags = []; foreach ( $recentChangesFlags as $key => $value ) { - $flagGrouping = ( isset( $recentChangesFlags[$key]['grouping'] ) ? - $recentChangesFlags[$key]['grouping'] : 'any' ); + $flagGrouping = ( $recentChangesFlags[$key]['grouping'] ?? 'any' ); switch ( $flagGrouping ) { case 'all': $collectedRcFlags[$key] = true; @@ -277,8 +276,7 @@ class EnhancedChangesList extends ChangesList { // Roll up flags foreach ( $line['recentChangesFlagsRaw'] as $key => $value ) { - $flagGrouping = ( isset( $recentChangesFlags[$key]['grouping'] ) ? - $recentChangesFlags[$key]['grouping'] : 'any' ); + $flagGrouping = ( $recentChangesFlags[$key]['grouping'] ?? 'any' ); switch ( $flagGrouping ) { case 'all': if ( !$value ) { diff --git a/includes/changes/RecentChange.php b/includes/changes/RecentChange.php index cc9532e064..60fe85009c 100644 --- a/includes/changes/RecentChange.php +++ b/includes/changes/RecentChange.php @@ -420,9 +420,9 @@ class RecentChange { # Convert mAttribs['rc_user'] etc for ActorMigration $user = User::newFromAnyId( - isset( $row['rc_user'] ) ? $row['rc_user'] : null, - isset( $row['rc_user_text'] ) ? $row['rc_user_text'] : null, - isset( $row['rc_actor'] ) ? $row['rc_actor'] : null + $row['rc_user'] ?? null, + $row['rc_user_text'] ?? null, + $row['rc_actor'] ?? null ); unset( $row['rc_user'], $row['rc_user_text'], $row['rc_actor'] ); $row += ActorMigration::newMigration()->getInsertValues( $dbw, 'rc_user', $user ); @@ -1024,7 +1024,7 @@ class RecentChange { */ public function getParam( $name ) { $params = $this->parseParams(); - return isset( $params[$name] ) ? $params[$name] : null; + return $params[$name] ?? null; } /** @@ -1055,9 +1055,9 @@ class RecentChange { $this->mAttribs['rc_comment_data'] = null; $user = User::newFromAnyId( - isset( $this->mAttribs['rc_user'] ) ? $this->mAttribs['rc_user'] : null, - isset( $this->mAttribs['rc_user_text'] ) ? $this->mAttribs['rc_user_text'] : null, - isset( $this->mAttribs['rc_actor'] ) ? $this->mAttribs['rc_actor'] : null + $this->mAttribs['rc_user'] ?? null, + $this->mAttribs['rc_user_text'] ?? null, + $this->mAttribs['rc_actor'] ?? null ); $this->mAttribs['rc_user'] = $user->getId(); $this->mAttribs['rc_user_text'] = $user->getName(); @@ -1078,9 +1078,9 @@ class RecentChange { if ( $name === 'rc_user' || $name === 'rc_user_text' || $name === 'rc_actor' ) { $user = User::newFromAnyId( - isset( $this->mAttribs['rc_user'] ) ? $this->mAttribs['rc_user'] : null, - isset( $this->mAttribs['rc_user_text'] ) ? $this->mAttribs['rc_user_text'] : null, - isset( $this->mAttribs['rc_actor'] ) ? $this->mAttribs['rc_actor'] : null + $this->mAttribs['rc_user'] ?? null, + $this->mAttribs['rc_user_text'] ?? null, + $this->mAttribs['rc_actor'] ?? null ); if ( $name === 'rc_user' ) { return $user->getId(); @@ -1093,7 +1093,7 @@ class RecentChange { } } - return isset( $this->mAttribs[$name] ) ? $this->mAttribs[$name] : null; + return $this->mAttribs[$name] ?? null; } /** diff --git a/includes/changetags/ChangeTags.php b/includes/changetags/ChangeTags.php index b64f85a9b4..429a3b69c5 100644 --- a/includes/changetags/ChangeTags.php +++ b/includes/changetags/ChangeTags.php @@ -1268,7 +1268,7 @@ class ChangeTags { // store the tag usage statistics $tagUsage = self::tagUsageStatistics(); - $hitcount = isset( $tagUsage[$tag] ) ? $tagUsage[$tag] : 0; + $hitcount = $tagUsage[$tag] ?? 0; // do it! $deleteResult = self::deleteTagEverywhere( $tag ); diff --git a/includes/clientpool/SquidPurgeClient.php b/includes/clientpool/SquidPurgeClient.php index 3388860508..a531cd1b13 100644 --- a/includes/clientpool/SquidPurgeClient.php +++ b/includes/clientpool/SquidPurgeClient.php @@ -73,7 +73,7 @@ class SquidPurgeClient { public function __construct( $server, $options = [] ) { $parts = explode( ':', $server, 2 ); $this->host = $parts[0]; - $this->port = isset( $parts[1] ) ? $parts[1] : 80; + $this->port = $parts[1] ?? 80; } /** diff --git a/includes/debug/logger/MonologSpi.php b/includes/debug/logger/MonologSpi.php index ec27ad1cdc..670ba391e7 100644 --- a/includes/debug/logger/MonologSpi.php +++ b/includes/debug/logger/MonologSpi.php @@ -179,9 +179,7 @@ class MonologSpi implements Spi { if ( !isset( $this->singletons['loggers'][$channel] ) ) { // Fallback to using the '@default' configuration if an explict // configuration for the requested channel isn't found. - $spec = isset( $this->config['loggers'][$channel] ) ? - $this->config['loggers'][$channel] : - $this->config['loggers']['@default']; + $spec = $this->config['loggers'][$channel] ?? $this->config['loggers']['@default']; $monolog = $this->createLogger( $channel, $spec ); $this->singletons['loggers'][$channel] = $monolog; diff --git a/includes/debug/logger/monolog/LineFormatter.php b/includes/debug/logger/monolog/LineFormatter.php index cdc4da3aa0..62d45d4c61 100644 --- a/includes/debug/logger/monolog/LineFormatter.php +++ b/includes/debug/logger/monolog/LineFormatter.php @@ -164,7 +164,7 @@ class LineFormatter extends MonologLineFormatter { ); } - $prev = isset( $prev['previous'] ) ? $prev['previous'] : null; + $prev = $prev['previous'] ?? null; } } return $str; diff --git a/includes/externalstore/ExternalStoreDB.php b/includes/externalstore/ExternalStoreDB.php index 5edb4b2ef0..45a6bafa88 100644 --- a/includes/externalstore/ExternalStoreDB.php +++ b/includes/externalstore/ExternalStoreDB.php @@ -128,7 +128,7 @@ class ExternalStoreDB extends ExternalStoreMedium { public function getSlave( $cluster ) { global $wgDefaultExternalStore; - $wiki = isset( $this->params['wiki'] ) ? $this->params['wiki'] : false; + $wiki = $this->params['wiki'] ?? false; $lb = $this->getLoadBalancer( $cluster ); if ( !in_array( "DB://" . $cluster, (array)$wgDefaultExternalStore ) ) { @@ -151,7 +151,7 @@ class ExternalStoreDB extends ExternalStoreMedium { * @return MaintainableDBConnRef */ public function getMaster( $cluster ) { - $wiki = isset( $this->params['wiki'] ) ? $this->params['wiki'] : false; + $wiki = $this->params['wiki'] ?? false; $lb = $this->getLoadBalancer( $cluster ); $db = $lb->getMaintenanceConnectionRef( DB_MASTER, [], $wiki ); @@ -301,7 +301,7 @@ class ExternalStoreDB extends ExternalStoreMedium { return [ $path[2], // cluster $path[3], // id - isset( $path[4] ) ? $path[4] : false // itemID + $path[4] ?? false // itemID ]; } } diff --git a/includes/externalstore/ExternalStoreMwstore.php b/includes/externalstore/ExternalStoreMwstore.php index 5d7155e8a7..c5893be678 100644 --- a/includes/externalstore/ExternalStoreMwstore.php +++ b/includes/externalstore/ExternalStoreMwstore.php @@ -81,7 +81,7 @@ class ExternalStoreMwstore extends ExternalStoreMedium { // Make sure ID is roughly lexicographically increasing for performance $id = str_pad( UIDGenerator::newTimestampedUID128( 32 ), 26, '0', STR_PAD_LEFT ); // Segregate items by wiki ID for the sake of bookkeeping - $wiki = isset( $this->params['wiki'] ) ? $this->params['wiki'] : wfWikiID(); + $wiki = $this->params['wiki'] ?? wfWikiID(); $url = $be->getContainerStoragePath( 'data' ) . '/' . rawurlencode( $wiki ); $url .= ( $be instanceof FSFileBackend ) diff --git a/includes/filebackend/FileBackendGroup.php b/includes/filebackend/FileBackendGroup.php index 454b6332fd..dc6dbe8f53 100644 --- a/includes/filebackend/FileBackendGroup.php +++ b/includes/filebackend/FileBackendGroup.php @@ -79,15 +79,9 @@ class FileBackendGroup { $repoName = $info['name']; // Local vars that used to be FSRepo members... $directory = $info['directory']; - $deletedDir = isset( $info['deletedDir'] ) - ? $info['deletedDir'] - : false; // deletion disabled - $thumbDir = isset( $info['thumbDir'] ) - ? $info['thumbDir'] - : "{$directory}/thumb"; - $transcodedDir = isset( $info['transcodedDir'] ) - ? $info['transcodedDir'] - : "{$directory}/transcoded"; + $deletedDir = $info['deletedDir'] ?? false; // deletion disabled + $thumbDir = $info['thumbDir'] ?? "{$directory}/thumb"; + $transcodedDir = $info['transcodedDir'] ?? "{$directory}/transcoded"; // Get the FS backend configuration $autoBackends[] = [ 'name' => $backendName, @@ -100,7 +94,7 @@ class FileBackendGroup { "{$repoName}-deleted" => $deletedDir, "{$repoName}-temp" => "{$directory}/temp" ], - 'fileMode' => isset( $info['fileMode'] ) ? $info['fileMode'] : 0644, + 'fileMode' => $info['fileMode'] ?? 0644, 'directoryMode' => $wgDirectoryMode, ]; } diff --git a/includes/filerepo/FileRepo.php b/includes/filerepo/FileRepo.php index b15f81fafe..89bb81a7c0 100644 --- a/includes/filerepo/FileRepo.php +++ b/includes/filerepo/FileRepo.php @@ -171,30 +171,20 @@ class FileRepo { } // Optional settings that have a default - $this->initialCapital = isset( $info['initialCapital'] ) - ? $info['initialCapital'] - : MWNamespace::isCapitalized( NS_FILE ); - $this->url = isset( $info['url'] ) - ? $info['url'] - : false; // a subclass may set the URL (e.g. ForeignAPIRepo) + $this->initialCapital = $info['initialCapital'] ?? MWNamespace::isCapitalized( NS_FILE ); + $this->url = $info['url'] ?? false; // a subclass may set the URL (e.g. ForeignAPIRepo) if ( isset( $info['thumbUrl'] ) ) { $this->thumbUrl = $info['thumbUrl']; } else { $this->thumbUrl = $this->url ? "{$this->url}/thumb" : false; } - $this->hashLevels = isset( $info['hashLevels'] ) - ? $info['hashLevels'] - : 2; - $this->deletedHashLevels = isset( $info['deletedHashLevels'] ) - ? $info['deletedHashLevels'] - : $this->hashLevels; + $this->hashLevels = $info['hashLevels'] ?? 2; + $this->deletedHashLevels = $info['deletedHashLevels'] ?? $this->hashLevels; $this->transformVia404 = !empty( $info['transformVia404'] ); - $this->abbrvThreshold = isset( $info['abbrvThreshold'] ) - ? $info['abbrvThreshold'] - : 255; + $this->abbrvThreshold = $info['abbrvThreshold'] ?? 255; $this->isPrivate = !empty( $info['isPrivate'] ); // Give defaults for the basic zones... - $this->zones = isset( $info['zones'] ) ? $info['zones'] : []; + $this->zones = $info['zones'] ?? []; foreach ( [ 'public', 'thumb', 'transcoded', 'temp', 'deleted' ] as $zone ) { if ( !isset( $this->zones[$zone]['container'] ) ) { $this->zones[$zone]['container'] = "{$this->name}-{$zone}"; @@ -428,7 +418,7 @@ class FileRepo { if ( isset( $options['bypassCache'] ) ) { $options['latest'] = $options['bypassCache']; // b/c } - $time = isset( $options['time'] ) ? $options['time'] : false; + $time = $options['time'] ?? false; $flags = !empty( $options['latest'] ) ? File::READ_LATEST : 0; # First try the current version of the file to see if it precedes the timestamp $img = $this->newFile( $title ); @@ -534,7 +524,7 @@ class FileRepo { * @return File|bool False on failure */ public function findFileFromKey( $sha1, $options = [] ) { - $time = isset( $options['time'] ) ? $options['time'] : false; + $time = $options['time'] ?? false; # First try to find a matching current version of a file... if ( !$this->fileFactoryKey ) { return false; // find-by-sha1 not supported @@ -690,7 +680,7 @@ class FileRepo { */ public function getTempHashPath( $suffix ) { $parts = explode( '!', $suffix, 2 ); // format is ! or just - $name = isset( $parts[1] ) ? $parts[1] : $suffix; // hash path is not based on timestamp + $name = $parts[1] ?? $suffix; // hash path is not based on timestamp return self::getHashPathForLevel( $name, $this->hashLevels ); } @@ -1225,7 +1215,7 @@ class FileRepo { list( $src, $dstRel, $archiveRel ) = $ntuple; $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src; - $options = isset( $ntuple[3] ) ? $ntuple[3] : []; + $options = $ntuple[3] ?? []; // Resolve source to a storage path if virtual $srcPath = $this->resolveToStoragePath( $srcPath ); if ( !$this->validateFilename( $dstRel ) ) { @@ -1250,7 +1240,7 @@ class FileRepo { } // Set any desired headers to be use in GET/HEAD responses - $headers = isset( $options['headers'] ) ? $options['headers'] : []; + $headers = $options['headers'] ?? []; // Archive destination file if it exists. // This will check if the archive file also exists and fail if does. diff --git a/includes/filerepo/ForeignAPIRepo.php b/includes/filerepo/ForeignAPIRepo.php index cba21c8870..c20df76e2b 100644 --- a/includes/filerepo/ForeignAPIRepo.php +++ b/includes/filerepo/ForeignAPIRepo.php @@ -75,7 +75,7 @@ class ForeignAPIRepo extends FileRepo { parent::__construct( $info ); // https://commons.wikimedia.org/w/api.php - $this->mApiBase = isset( $info['apibase'] ) ? $info['apibase'] : null; + $this->mApiBase = $info['apibase'] ?? null; if ( isset( $info['apiThumbCacheExpiry'] ) ) { $this->apiThumbCacheExpiry = $info['apiThumbCacheExpiry']; diff --git a/includes/filerepo/RepoGroup.php b/includes/filerepo/RepoGroup.php index b7977900a3..005618126c 100644 --- a/includes/filerepo/RepoGroup.php +++ b/includes/filerepo/RepoGroup.php @@ -140,7 +140,7 @@ class RepoGroup { && empty( $options['private'] ) && empty( $options['latest'] ) ) { - $time = isset( $options['time'] ) ? $options['time'] : ''; + $time = $options['time'] ?? ''; if ( $this->cache->has( $dbkey, $time, 60 ) ) { return $this->cache->get( $dbkey, $time ); } diff --git a/includes/filerepo/file/File.php b/includes/filerepo/file/File.php index 7c87af3974..546b78a0b5 100644 --- a/includes/filerepo/file/File.php +++ b/includes/filerepo/file/File.php @@ -933,7 +933,7 @@ abstract class File implements IDBAccessObject { */ function getUnscaledThumb( $handlerParams = [] ) { $hp =& $handlerParams; - $page = isset( $hp['page'] ) ? $hp['page'] : false; + $page = $hp['page'] ?? false; $width = $this->getWidth( $page ); if ( !$width ) { return $this->iconThumb(); diff --git a/includes/filerepo/file/ForeignAPIFile.php b/includes/filerepo/file/ForeignAPIFile.php index 1002b82c52..0e48195c6e 100644 --- a/includes/filerepo/file/ForeignAPIFile.php +++ b/includes/filerepo/file/ForeignAPIFile.php @@ -128,8 +128,8 @@ class ForeignAPIFile extends File { // Note, the this->canRender() check above implies // that we have a handler, and it can do makeParamString. $otherParams = $this->handler->makeParamString( $params ); - $width = isset( $params['width'] ) ? $params['width'] : -1; - $height = isset( $params['height'] ) ? $params['height'] : -1; + $width = $params['width'] ?? -1; + $height = $params['height'] ?? -1; $thumbUrl = $this->repo->getThumbUrlFromCache( $this->getName(), @@ -311,9 +311,7 @@ class ForeignAPIFile extends File { * @return bool|string */ function getDescriptionUrl() { - return isset( $this->mInfo['descriptionurl'] ) - ? $this->mInfo['descriptionurl'] - : false; + return $this->mInfo['descriptionurl'] ?? false; } /** diff --git a/includes/filerepo/file/LocalFile.php b/includes/filerepo/file/LocalFile.php index 1702264045..adad9ad15f 100644 --- a/includes/filerepo/file/LocalFile.php +++ b/includes/filerepo/file/LocalFile.php @@ -583,9 +583,9 @@ class LocalFile extends File { ->getComment( 'description', (object)$decoded )->text; $decoded['user'] = User::newFromAnyId( - isset( $decoded['user'] ) ? $decoded['user'] : null, - isset( $decoded['user_text'] ) ? $decoded['user_text'] : null, - isset( $decoded['actor'] ) ? $decoded['actor'] : null + $decoded['user'] ?? null, + $decoded['user_text'] ?? null, + $decoded['actor'] ?? null ); unset( $decoded['user_text'], $decoded['actor'] ); @@ -772,9 +772,9 @@ class LocalFile extends File { if ( isset( $info['user'] ) || isset( $info['user_text'] ) || isset( $info['actor'] ) ) { $this->user = User::newFromAnyId( - isset( $info['user'] ) ? $info['user'] : null, - isset( $info['user_text'] ) ? $info['user_text'] : null, - isset( $info['actor'] ) ? $info['actor'] : null + $info['user'] ?? null, + $info['user_text'] ?? null, + $info['actor'] ?? null ); } diff --git a/includes/gallery/TraditionalImageGallery.php b/includes/gallery/TraditionalImageGallery.php index cd6aab0f88..a87322d46d 100644 --- a/includes/gallery/TraditionalImageGallery.php +++ b/includes/gallery/TraditionalImageGallery.php @@ -35,7 +35,7 @@ class TraditionalImageGallery extends ImageGalleryBase { function toHTML() { if ( $this->mPerRow > 0 ) { $maxwidth = $this->mPerRow * ( $this->mWidths + $this->getAllPadding() ); - $oldStyle = isset( $this->mAttribs['style'] ) ? $this->mAttribs['style'] : ''; + $oldStyle = $this->mAttribs['style'] ?? ''; # _width is ignored by any sane browser. IE6 doesn't know max-width # so it uses _width instead $this->mAttribs['style'] = "max-width: {$maxwidth}px;_width: {$maxwidth}px;" . diff --git a/includes/htmlform/HTMLForm.php b/includes/htmlform/HTMLForm.php index 043e0f632b..785d30f8a3 100644 --- a/includes/htmlform/HTMLForm.php +++ b/includes/htmlform/HTMLForm.php @@ -333,9 +333,7 @@ class HTMLForm extends ContextSource { $this->mFlatFields = []; foreach ( $descriptor as $fieldname => $info ) { - $section = isset( $info['section'] ) - ? $info['section'] - : ''; + $section = $info['section'] ?? ''; if ( isset( $info['type'] ) && $info['type'] === 'file' ) { $this->mUseMultipart = true; @@ -805,7 +803,7 @@ class HTMLForm extends ContextSource { if ( $section === null ) { return $this->mHeader; } else { - return isset( $this->mSectionHeaders[$section] ) ? $this->mSectionHeaders[$section] : ''; + return $this->mSectionHeaders[$section] ?? ''; } } @@ -860,7 +858,7 @@ class HTMLForm extends ContextSource { if ( $section === null ) { return $this->mFooter; } else { - return isset( $this->mSectionFooters[$section] ) ? $this->mSectionFooters[$section] : ''; + return $this->mSectionFooters[$section] ?? ''; } } @@ -959,8 +957,8 @@ class HTMLForm extends ContextSource { $data = [ 'name' => $args[0], 'value' => $args[1], - 'id' => isset( $args[2] ) ? $args[2] : null, - 'attribs' => isset( $args[3] ) ? $args[3] : null, + 'id' => $args[2] ?? null, + 'attribs' => $args[3] ?? null, ]; } else { if ( !isset( $data['name'] ) ) { diff --git a/includes/htmlform/HTMLFormElement.php b/includes/htmlform/HTMLFormElement.php index 2830b9c258..fbef2651f6 100644 --- a/includes/htmlform/HTMLFormElement.php +++ b/includes/htmlform/HTMLFormElement.php @@ -13,8 +13,8 @@ trait HTMLFormElement { public function initializeHTMLFormElement( array $config = [] ) { // Properties - $this->hideIf = isset( $config['hideIf'] ) ? $config['hideIf'] : null; - $this->modules = isset( $config['modules'] ) ? $config['modules'] : []; + $this->hideIf = $config['hideIf'] ?? null; + $this->modules = $config['modules'] ?? []; // Initialization if ( $this->hideIf ) { diff --git a/includes/htmlform/HTMLFormField.php b/includes/htmlform/HTMLFormField.php index 5066f28ee4..cd4d4b749f 100644 --- a/includes/htmlform/HTMLFormField.php +++ b/includes/htmlform/HTMLFormField.php @@ -546,8 +546,7 @@ abstract class HTMLFormField { 'mw-htmlform-nolabel' => ( $label === '' ) ]; - $horizontalLabel = isset( $this->mParams['horizontal-label'] ) - ? $this->mParams['horizontal-label'] : false; + $horizontalLabel = $this->mParams['horizontal-label'] ?? false; if ( $horizontalLabel ) { $field = ' ' . $inputHtml . "\n$errors"; @@ -950,8 +949,7 @@ abstract class HTMLFormField { $displayFormat = $this->mParent->getDisplayFormat(); $html = ''; - $horizontalLabel = isset( $this->mParams['horizontal-label'] ) - ? $this->mParams['horizontal-label'] : false; + $horizontalLabel = $this->mParams['horizontal-label'] ?? false; if ( $displayFormat === 'table' ) { $html = diff --git a/includes/htmlform/fields/HTMLExpiryField.php b/includes/htmlform/fields/HTMLExpiryField.php index dfe6a8a623..e7bdb44b85 100644 --- a/includes/htmlform/fields/HTMLExpiryField.php +++ b/includes/htmlform/fields/HTMLExpiryField.php @@ -56,7 +56,7 @@ class HTMLExpiryField extends HTMLFormField { $this->relativeField->getInputOOUI( $value ), [ 'id' => $this->mID, - 'required' => isset( $this->mParams['required'] ) ? $this->mParams['required'] : false, + 'required' => $this->mParams['required'] ?? false, ] ); } diff --git a/includes/htmlform/fields/HTMLFloatField.php b/includes/htmlform/fields/HTMLFloatField.php index d2d54e28d0..72381f0161 100644 --- a/includes/htmlform/fields/HTMLFloatField.php +++ b/includes/htmlform/fields/HTMLFloatField.php @@ -5,7 +5,7 @@ */ class HTMLFloatField extends HTMLTextField { public function getSize() { - return isset( $this->mParams['size'] ) ? $this->mParams['size'] : 20; + return $this->mParams['size'] ?? 20; } public function validate( $value, $alldata ) { diff --git a/includes/htmlform/fields/HTMLFormFieldCloner.php b/includes/htmlform/fields/HTMLFormFieldCloner.php index 53c6835949..6beb996667 100644 --- a/includes/htmlform/fields/HTMLFormFieldCloner.php +++ b/includes/htmlform/fields/HTMLFormFieldCloner.php @@ -273,9 +273,7 @@ class HTMLFormFieldCloner extends HTMLFormField { * @return string */ protected function getInputHTMLForKey( $key, array $values ) { - $displayFormat = isset( $this->mParams['format'] ) - ? $this->mParams['format'] - : $this->mParent->getDisplayFormat(); + $displayFormat = $this->mParams['format'] ?? $this->mParent->getDisplayFormat(); // Conveniently, PHP method names are case-insensitive. $getFieldHtmlMethod = $displayFormat == 'table' ? 'getTableRow' : ( 'get' . $displayFormat ); @@ -306,9 +304,7 @@ class HTMLFormFieldCloner extends HTMLFormField { if ( !isset( $fields['delete'] ) ) { $name = "{$this->mName}[$key][delete]"; - $label = isset( $this->mParams['delete-button-message'] ) - ? $this->mParams['delete-button-message'] - : 'htmlform-cloner-delete'; + $label = $this->mParams['delete-button-message'] ?? 'htmlform-cloner-delete'; $field = HTMLForm::loadInputFromParameters( $name, [ 'type' => 'submit', 'formnovalidate' => true, @@ -379,9 +375,7 @@ class HTMLFormFieldCloner extends HTMLFormField { ], $html ); $name = "{$this->mName}[create]"; - $label = isset( $this->mParams['create-button-message'] ) - ? $this->mParams['create-button-message'] - : 'htmlform-cloner-create'; + $label = $this->mParams['create-button-message'] ?? 'htmlform-cloner-create'; $field = HTMLForm::loadInputFromParameters( $name, [ 'type' => 'submit', 'formnovalidate' => true, diff --git a/includes/htmlform/fields/HTMLSelectAndOtherField.php b/includes/htmlform/fields/HTMLSelectAndOtherField.php index 610b509305..a4d9bca67b 100644 --- a/includes/htmlform/fields/HTMLSelectAndOtherField.php +++ b/includes/htmlform/fields/HTMLSelectAndOtherField.php @@ -126,8 +126,7 @@ class HTMLSelectAndOtherField extends HTMLSelectField { 'or' => false, 'classes' => [ 'mw-htmlform-select-and-other-field' ], 'data' => [ - 'maxlengthUnit' => isset( $this->mParams['maxlength-unit'] ) - ? $this->mParams['maxlength-unit'] : 'bytes' + 'maxlengthUnit' => $this->mParams['maxlength-unit'] ?? 'bytes' ], ] ); } @@ -177,7 +176,7 @@ class HTMLSelectAndOtherField extends HTMLSelectField { } public function getSize() { - return isset( $this->mParams['size'] ) ? $this->mParams['size'] : 45; + return $this->mParams['size'] ?? 45; } public function validate( $value, $alldata ) { diff --git a/includes/htmlform/fields/HTMLSelectOrOtherField.php b/includes/htmlform/fields/HTMLSelectOrOtherField.php index fb133f20e5..91050a0cc6 100644 --- a/includes/htmlform/fields/HTMLSelectOrOtherField.php +++ b/includes/htmlform/fields/HTMLSelectOrOtherField.php @@ -12,9 +12,7 @@ class HTMLSelectOrOtherField extends HTMLTextField { $this->getOptions(); if ( !in_array( 'other', $this->mOptions, true ) ) { $msg = - isset( $params['other'] ) - ? $params['other'] - : wfMessage( 'htmlform-selectorother-other' )->text(); + $params['other'] ?? wfMessage( 'htmlform-selectorother-other' )->text(); // Have 'other' always as first element $this->mOptions = [ $msg => 'other' ] + $this->mOptions; } diff --git a/includes/htmlform/fields/HTMLSizeFilterField.php b/includes/htmlform/fields/HTMLSizeFilterField.php index 145a0ecdb2..bd96d3c61f 100644 --- a/includes/htmlform/fields/HTMLSizeFilterField.php +++ b/includes/htmlform/fields/HTMLSizeFilterField.php @@ -10,7 +10,7 @@ */ class HTMLSizeFilterField extends HTMLIntField { public function getSize() { - return isset( $this->mParams['size'] ) ? $this->mParams['size'] : 9; + return $this->mParams['size'] ?? 9; } public function getInputHTML( $value ) { diff --git a/includes/htmlform/fields/HTMLTextAreaField.php b/includes/htmlform/fields/HTMLTextAreaField.php index 3370e4af13..e9ed031982 100644 --- a/includes/htmlform/fields/HTMLTextAreaField.php +++ b/includes/htmlform/fields/HTMLTextAreaField.php @@ -29,15 +29,15 @@ class HTMLTextAreaField extends HTMLFormField { } public function getCols() { - return isset( $this->mParams['cols'] ) ? $this->mParams['cols'] : static::DEFAULT_COLS; + return $this->mParams['cols'] ?? static::DEFAULT_COLS; } public function getRows() { - return isset( $this->mParams['rows'] ) ? $this->mParams['rows'] : static::DEFAULT_ROWS; + return $this->mParams['rows'] ?? static::DEFAULT_ROWS; } public function getSpellCheck() { - $val = isset( $this->mParams['spellcheck'] ) ? $this->mParams['spellcheck'] : null; + $val = $this->mParams['spellcheck'] ?? null; if ( is_bool( $val ) ) { // "spellcheck" attribute literally requires "true" or "false" to work. return $val === true ? 'true' : 'false'; diff --git a/includes/htmlform/fields/HTMLTextField.php b/includes/htmlform/fields/HTMLTextField.php index b2e4f2a559..b51182a2da 100644 --- a/includes/htmlform/fields/HTMLTextField.php +++ b/includes/htmlform/fields/HTMLTextField.php @@ -38,11 +38,11 @@ class HTMLTextField extends HTMLFormField { } public function getSize() { - return isset( $this->mParams['size'] ) ? $this->mParams['size'] : 45; + return $this->mParams['size'] ?? 45; } public function getSpellCheck() { - $val = isset( $this->mParams['spellcheck'] ) ? $this->mParams['spellcheck'] : null; + $val = $this->mParams['spellcheck'] ?? null; if ( is_bool( $val ) ) { // "spellcheck" attribute literally requires "true" or "false" to work. return $val === true ? 'true' : 'false'; @@ -107,7 +107,7 @@ class HTMLTextField extends HTMLFormField { } protected function getType( &$attribs ) { - $type = isset( $attribs['type'] ) ? $attribs['type'] : 'text'; + $type = $attribs['type'] ?? 'text'; unset( $attribs['type'] ); # Implement tiny differences between some field variants diff --git a/includes/import/WikiImporter.php b/includes/import/WikiImporter.php index 8991f5ef4d..e5dacd70bc 100644 --- a/includes/import/WikiImporter.php +++ b/includes/import/WikiImporter.php @@ -784,7 +784,7 @@ class WikiImporter { } elseif ( $tag == 'revision' || $tag == 'upload' ) { if ( !isset( $title ) ) { $title = $this->processTitle( $pageInfo['title'], - isset( $pageInfo['ns'] ) ? $pageInfo['ns'] : null ); + $pageInfo['ns'] ?? null ); // $title is either an array of two titles or false. if ( is_array( $title ) ) { @@ -1015,7 +1015,7 @@ class WikiImporter { */ private function processUpload( $pageInfo, $uploadInfo ) { $revision = new WikiRevision( $this->config ); - $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : ''; + $text = $uploadInfo['text'] ?? ''; $revision->setTitle( $pageInfo['_title'] ); $revision->setID( $pageInfo['id'] ); diff --git a/includes/installer/CliInstaller.php b/includes/installer/CliInstaller.php index 715f5dff1f..728c23765a 100644 --- a/includes/installer/CliInstaller.php +++ b/includes/installer/CliInstaller.php @@ -97,7 +97,7 @@ class CliInstaller extends Installer { $this->setVar( '_InstallUser', $option['installdbuser'] ); $this->setVar( '_InstallPassword', - isset( $option['installdbpass'] ) ? $option['installdbpass'] : "" ); + $option['installdbpass'] ?? "" ); // Assume that if we're given the installer user, we'll create the account. $this->setVar( '_CreateDBAccount', true ); diff --git a/includes/installer/WebInstallerExistingWiki.php b/includes/installer/WebInstallerExistingWiki.php index df68be8ef6..0c7428fafc 100644 --- a/includes/installer/WebInstallerExistingWiki.php +++ b/includes/installer/WebInstallerExistingWiki.php @@ -180,9 +180,7 @@ class WebInstallerExistingWiki extends WebInstallerPage { // Copy $wgAuthenticationTokenVersion too, if it exists $this->setVar( 'wgAuthenticationTokenVersion', - isset( $vars['wgAuthenticationTokenVersion'] ) - ? $vars['wgAuthenticationTokenVersion'] - : null + $vars['wgAuthenticationTokenVersion'] ?? null ); return $status; diff --git a/includes/interwiki/ClassicInterwikiLookup.php b/includes/interwiki/ClassicInterwikiLookup.php index d5103da977..eada9d40ca 100644 --- a/includes/interwiki/ClassicInterwikiLookup.php +++ b/includes/interwiki/ClassicInterwikiLookup.php @@ -314,10 +314,10 @@ class ClassicInterwikiLookup implements InterwikiLookup { private function loadFromArray( $mc ) { if ( isset( $mc['iw_url'] ) ) { $url = $mc['iw_url']; - $local = isset( $mc['iw_local'] ) ? $mc['iw_local'] : 0; - $trans = isset( $mc['iw_trans'] ) ? $mc['iw_trans'] : 0; - $api = isset( $mc['iw_api'] ) ? $mc['iw_api'] : ''; - $wikiId = isset( $mc['iw_wikiid'] ) ? $mc['iw_wikiid'] : ''; + $local = $mc['iw_local'] ?? 0; + $trans = $mc['iw_trans'] ?? 0; + $api = $mc['iw_api'] ?? ''; + $wikiId = $mc['iw_wikiid'] ?? ''; return new Interwiki( null, $url, $api, $wikiId, $local, $trans ); } diff --git a/includes/jobqueue/Job.php b/includes/jobqueue/Job.php index b16cfa3819..45ab4d342f 100644 --- a/includes/jobqueue/Job.php +++ b/includes/jobqueue/Job.php @@ -170,9 +170,7 @@ abstract class Job implements IJobSpecification { * @since 1.27 */ public function getRequestId() { - return isset( $this->params['requestId'] ) - ? $this->params['requestId'] - : null; + return $this->params['requestId'] ?? null; } /** @@ -280,12 +278,8 @@ abstract class Job implements IJobSpecification { */ public function getRootJobParams() { return [ - 'rootJobSignature' => isset( $this->params['rootJobSignature'] ) - ? $this->params['rootJobSignature'] - : null, - 'rootJobTimestamp' => isset( $this->params['rootJobTimestamp'] ) - ? $this->params['rootJobTimestamp'] - : null + 'rootJobSignature' => $this->params['rootJobSignature'] ?? null, + 'rootJobTimestamp' => $this->params['rootJobTimestamp'] ?? null ]; } diff --git a/includes/jobqueue/JobQueue.php b/includes/jobqueue/JobQueue.php index d2446abbfa..c4ce2ba9b1 100644 --- a/includes/jobqueue/JobQueue.php +++ b/includes/jobqueue/JobQueue.php @@ -58,8 +58,8 @@ abstract class JobQueue { protected function __construct( array $params ) { $this->wiki = $params['wiki']; $this->type = $params['type']; - $this->claimTTL = isset( $params['claimTTL'] ) ? $params['claimTTL'] : 0; - $this->maxTries = isset( $params['maxTries'] ) ? $params['maxTries'] : 3; + $this->claimTTL = $params['claimTTL'] ?? 0; + $this->maxTries = $params['maxTries'] ?? 3; if ( isset( $params['order'] ) && $params['order'] !== 'any' ) { $this->order = $params['order']; } else { @@ -69,12 +69,8 @@ abstract class JobQueue { throw new MWException( __CLASS__ . " does not support '{$this->order}' order." ); } $this->dupCache = wfGetCache( CACHE_ANYTHING ); - $this->aggr = isset( $params['aggregator'] ) - ? $params['aggregator'] - : new JobQueueAggregatorNull( [] ); - $this->readOnlyReason = isset( $params['readOnlyReason'] ) - ? $params['readOnlyReason'] - : false; + $this->aggr = $params['aggregator'] ?? new JobQueueAggregatorNull( [] ); + $this->readOnlyReason = $params['readOnlyReason'] ?? false; } /** diff --git a/includes/jobqueue/JobQueueDB.php b/includes/jobqueue/JobQueueDB.php index a082d647f2..bc737188f9 100644 --- a/includes/jobqueue/JobQueueDB.php +++ b/includes/jobqueue/JobQueueDB.php @@ -55,7 +55,7 @@ class JobQueueDB extends JobQueue { protected function __construct( array $params ) { parent::__construct( $params ); - $this->cluster = isset( $params['cluster'] ) ? $params['cluster'] : false; + $this->cluster = $params['cluster'] ?? false; $this->cache = ObjectCache::getMainWANInstance(); } diff --git a/includes/jobqueue/JobQueueFederated.php b/includes/jobqueue/JobQueueFederated.php index 7f3b2b1d59..0f8fcfbedb 100644 --- a/includes/jobqueue/JobQueueFederated.php +++ b/includes/jobqueue/JobQueueFederated.php @@ -73,15 +73,11 @@ class JobQueueFederated extends JobQueue { */ protected function __construct( array $params ) { parent::__construct( $params ); - $section = isset( $params['sectionsByWiki'][$this->wiki] ) - ? $params['sectionsByWiki'][$this->wiki] - : 'default'; + $section = $params['sectionsByWiki'][$this->wiki] ?? 'default'; if ( !isset( $params['partitionsBySection'][$section] ) ) { throw new MWException( "No configuration for section '$section'." ); } - $this->maxPartitionsTry = isset( $params['maxPartitionsTry'] ) - ? $params['maxPartitionsTry'] - : 2; + $this->maxPartitionsTry = $params['maxPartitionsTry'] ?? 2; // Get the full partition map $partitionMap = $params['partitionsBySection'][$section]; arsort( $partitionMap, SORT_NUMERIC ); diff --git a/includes/jobqueue/JobQueueRedis.php b/includes/jobqueue/JobQueueRedis.php index 7dad014e45..e9505bcfb4 100644 --- a/includes/jobqueue/JobQueueRedis.php +++ b/includes/jobqueue/JobQueueRedis.php @@ -93,7 +93,7 @@ class JobQueueRedis extends JobQueue { parent::__construct( $params ); $params['redisConfig']['serializer'] = 'none'; // make it easy to use Lua $this->server = $params['redisServer']; - $this->compression = isset( $params['compression'] ) ? $params['compression'] : 'none'; + $this->compression = $params['compression'] ?? 'none'; $this->redisPool = RedisConnectionPool::singleton( $params['redisConfig'] ); if ( empty( $params['daemonized'] ) ) { throw new InvalidArgumentException( diff --git a/includes/jobqueue/JobQueueSecondTestQueue.php b/includes/jobqueue/JobQueueSecondTestQueue.php index 01f467f20b..e63f01fc2c 100644 --- a/includes/jobqueue/JobQueueSecondTestQueue.php +++ b/includes/jobqueue/JobQueueSecondTestQueue.php @@ -44,7 +44,7 @@ class JobQueueSecondTestQueue extends JobQueue { $conf = [ 'wiki' => $params['wiki'], 'type' => $params['type'] ]; $this->mainQueue = JobQueue::factory( $params['mainqueue'] + $conf ); $this->debugQueue = JobQueue::factory( $params['debugqueue'] + $conf ); - $this->onlyWriteToDebugQueue = isset( $params['readonly'] ) ? $params['readonly'] : false; + $this->onlyWriteToDebugQueue = $params['readonly'] ?? false; // We need to construct parent after creating the main and debug queue // because super constructor calls some methods we delegate to the main queue. diff --git a/includes/jobqueue/JobRunner.php b/includes/jobqueue/JobRunner.php index 977fbdaaa5..a85613af48 100644 --- a/includes/jobqueue/JobRunner.php +++ b/includes/jobqueue/JobRunner.php @@ -109,9 +109,9 @@ class JobRunner implements LoggerAwareInterface { $response = [ 'jobs' => [], 'reached' => 'none-ready' ]; - $type = isset( $options['type'] ) ? $options['type'] : false; - $maxJobs = isset( $options['maxJobs'] ) ? $options['maxJobs'] : false; - $maxTime = isset( $options['maxTime'] ) ? $options['maxTime'] : false; + $type = $options['type'] ?? false; + $maxJobs = $options['maxJobs'] ?? false; + $maxTime = $options['maxTime'] ?? false; $noThrottle = isset( $options['throttle'] ) && !$options['throttle']; // Bail if job type is invalid diff --git a/includes/jobqueue/JobSpecification.php b/includes/jobqueue/JobSpecification.php index b62b83c666..af5646aa92 100644 --- a/includes/jobqueue/JobSpecification.php +++ b/includes/jobqueue/JobSpecification.php @@ -186,12 +186,8 @@ class JobSpecification implements IJobSpecification { public function getRootJobParams() { return [ - 'rootJobSignature' => isset( $this->params['rootJobSignature'] ) - ? $this->params['rootJobSignature'] - : null, - 'rootJobTimestamp' => isset( $this->params['rootJobTimestamp'] ) - ? $this->params['rootJobTimestamp'] - : null + 'rootJobSignature' => $this->params['rootJobSignature'] ?? null, + 'rootJobTimestamp' => $this->params['rootJobTimestamp'] ?? null ]; } diff --git a/includes/jobqueue/aggregator/JobQueueAggregatorRedis.php b/includes/jobqueue/aggregator/JobQueueAggregatorRedis.php index db07086f21..7d0e1e643a 100644 --- a/includes/jobqueue/aggregator/JobQueueAggregatorRedis.php +++ b/includes/jobqueue/aggregator/JobQueueAggregatorRedis.php @@ -49,9 +49,7 @@ class JobQueueAggregatorRedis extends JobQueueAggregator { */ public function __construct( array $params ) { parent::__construct( $params ); - $this->servers = isset( $params['redisServers'] ) - ? $params['redisServers'] - : [ $params['redisServer'] ]; // b/c + $this->servers = $params['redisServers'] ?? [ $params['redisServer'] ]; // b/c $params['redisConfig']['serializer'] = 'none'; $this->redisPool = RedisConnectionPool::singleton( $params['redisConfig'] ); $this->logger = \MediaWiki\Logger\LoggerFactory::getInstance( 'redis' ); diff --git a/includes/jobqueue/jobs/DeleteLinksJob.php b/includes/jobqueue/jobs/DeleteLinksJob.php index d0969e4631..0a1419212b 100644 --- a/includes/jobqueue/jobs/DeleteLinksJob.php +++ b/includes/jobqueue/jobs/DeleteLinksJob.php @@ -55,7 +55,7 @@ class DeleteLinksJob extends Job { } $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory(); - $timestamp = isset( $this->params['timestamp'] ) ? $this->params['timestamp'] : null; + $timestamp = $this->params['timestamp'] ?? null; $page = WikiPage::factory( $this->title ); // title when deleted $update = new LinksDeletionUpdate( $page, $pageId, $timestamp ); diff --git a/includes/jobqueue/jobs/HTMLCacheUpdateJob.php b/includes/jobqueue/jobs/HTMLCacheUpdateJob.php index 34028df172..7d0ada5e97 100644 --- a/includes/jobqueue/jobs/HTMLCacheUpdateJob.php +++ b/includes/jobqueue/jobs/HTMLCacheUpdateJob.php @@ -128,9 +128,7 @@ class HTMLCacheUpdateJob extends Job { // not expected to invalidate these cache entries too often. $touchTimestamp = wfTimestampNow(); // If page_touched is higher than this, then something else already bumped it after enqueue - $condTimestamp = isset( $this->params['rootJobTimestamp'] ) - ? $this->params['rootJobTimestamp'] - : $touchTimestamp; + $condTimestamp = $this->params['rootJobTimestamp'] ?? $touchTimestamp; $dbw = wfGetDB( DB_MASTER ); $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory(); diff --git a/includes/jobqueue/jobs/PublishStashedFileJob.php b/includes/jobqueue/jobs/PublishStashedFileJob.php index e89812beff..d2b2107151 100644 --- a/includes/jobqueue/jobs/PublishStashedFileJob.php +++ b/includes/jobqueue/jobs/PublishStashedFileJob.php @@ -84,7 +84,7 @@ class PublishStashedFileJob extends Job { $this->params['text'], $this->params['watch'], $user, - isset( $this->params['tags'] ) ? $this->params['tags'] : [] + $this->params['tags'] ?? [] ); if ( !$status->isGood() ) { UploadBase::setSessionStatus( diff --git a/includes/jobqueue/utils/BacklinkJobUtils.php b/includes/jobqueue/utils/BacklinkJobUtils.php index 76f8d6d2ac..bf27e9cf70 100644 --- a/includes/jobqueue/utils/BacklinkJobUtils.php +++ b/includes/jobqueue/utils/BacklinkJobUtils.php @@ -103,7 +103,7 @@ class BacklinkJobUtils { $realBSize = $bSize; } - $extraParams = isset( $opts['params'] ) ? $opts['params'] : []; + $extraParams = $opts['params'] ?? []; $jobs = []; // Combine the first range (of size $bSize) backlinks into leaf jobs diff --git a/includes/libs/HttpStatus.php b/includes/libs/HttpStatus.php index 7e652162b2..4b14160501 100644 --- a/includes/libs/HttpStatus.php +++ b/includes/libs/HttpStatus.php @@ -84,7 +84,7 @@ class HttpStatus { 507 => 'Insufficient Storage', 511 => 'Network Authentication Required', ]; - return isset( $statusMessage[$code] ) ? $statusMessage[$code] : null; + return $statusMessage[$code] ?? null; } /** diff --git a/includes/libs/JavaScriptMinifier.php b/includes/libs/JavaScriptMinifier.php index 43cd7db2d1..2e8b5919f4 100644 --- a/includes/libs/JavaScriptMinifier.php +++ b/includes/libs/JavaScriptMinifier.php @@ -575,7 +575,7 @@ class JavaScriptMinifier { // Now get the token type from our type array $token = substr( $s, $pos, $end - $pos ); // so $end - $pos == strlen( $token ) - $type = isset( $tokenTypes[$token] ) ? $tokenTypes[$token] : self::TYPE_LITERAL; + $type = $tokenTypes[$token] ?? self::TYPE_LITERAL; if ( $newlineFound && isset( $semicolon[$state][$type] ) ) { // This token triggers the semicolon insertion mechanism of javascript. While we diff --git a/includes/libs/MappedIterator.php b/includes/libs/MappedIterator.php index d60af343c0..4a62e72909 100644 --- a/includes/libs/MappedIterator.php +++ b/includes/libs/MappedIterator.php @@ -60,7 +60,7 @@ class MappedIterator extends FilterIterator { } parent::__construct( $baseIterator ); $this->vCallback = $vCallback; - $this->aCallback = isset( $options['accept'] ) ? $options['accept'] : null; + $this->aCallback = $options['accept'] ?? null; } public function next() { diff --git a/includes/libs/MultiHttpClient.php b/includes/libs/MultiHttpClient.php index d75d698ce8..cb60b019e4 100644 --- a/includes/libs/MultiHttpClient.php +++ b/includes/libs/MultiHttpClient.php @@ -172,7 +172,7 @@ class MultiHttpClient implements LoggerAwareInterface { throw new Exception( "Request has no 'url' field set." ); } $this->logger->debug( "{$req['method']}: {$req['url']}" ); - $req['query'] = isset( $req['query'] ) ? $req['query'] : []; + $req['query'] = $req['query'] ?? []; $headers = []; // normalized headers if ( isset( $req['headers'] ) ) { foreach ( $req['headers'] as $name => $value ) { @@ -184,7 +184,7 @@ class MultiHttpClient implements LoggerAwareInterface { $req['body'] = ''; $req['headers']['content-length'] = 0; } - $req['flags'] = isset( $req['flags'] ) ? $req['flags'] : []; + $req['flags'] = $req['flags'] ?? []; $handles[$index] = $this->getCurlHandle( $req, $opts ); if ( count( $reqs ) > 1 ) { // https://github.com/guzzle/guzzle/issues/349 @@ -286,10 +286,10 @@ class MultiHttpClient implements LoggerAwareInterface { $ch = curl_init(); curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, - isset( $opts['connTimeout'] ) ? $opts['connTimeout'] : $this->connTimeout ); - curl_setopt( $ch, CURLOPT_PROXY, isset( $req['proxy'] ) ? $req['proxy'] : $this->proxy ); + $opts['connTimeout'] ?? $this->connTimeout ); + curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy ); curl_setopt( $ch, CURLOPT_TIMEOUT, - isset( $opts['reqTimeout'] ) ? $opts['reqTimeout'] : $this->reqTimeout ); + $opts['reqTimeout'] ?? $this->reqTimeout ); curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 ); curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 ); curl_setopt( $ch, CURLOPT_HEADER, 0 ); diff --git a/includes/libs/Timing.php b/includes/libs/Timing.php index 73afbb2d96..04a13e2c69 100644 --- a/includes/libs/Timing.php +++ b/includes/libs/Timing.php @@ -52,7 +52,7 @@ class Timing implements LoggerAwareInterface { public function __construct( array $params = [] ) { $this->clearMarks(); - $this->setLogger( isset( $params['logger'] ) ? $params['logger'] : new NullLogger() ); + $this->setLogger( $params['logger'] ?? new NullLogger() ); } /** @@ -188,6 +188,6 @@ class Timing implements LoggerAwareInterface { * @return array|null Entry named $name or null if it does not exist. */ public function getEntryByName( $name ) { - return isset( $this->entries[$name] ) ? $this->entries[$name] : null; + return $this->entries[$name] ?? null; } } diff --git a/includes/libs/UDPTransport.php b/includes/libs/UDPTransport.php index 7fad882a24..7532ce72b9 100644 --- a/includes/libs/UDPTransport.php +++ b/includes/libs/UDPTransport.php @@ -54,7 +54,7 @@ class UDPTransport { // IPv6 bracketed host $host = $m[1]; $port = intval( $m[2] ); - $prefix = isset( $m[3] ) ? $m[3] : false; + $prefix = $m[3] ?? false; $domain = AF_INET6; } elseif ( preg_match( '!^udp:(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $info, $m ) ) { $host = $m[1]; @@ -62,7 +62,7 @@ class UDPTransport { $host = gethostbyname( $host ); } $port = intval( $m[2] ); - $prefix = isset( $m[3] ) ? $m[3] : false; + $prefix = $m[3] ?? false; $domain = AF_INET; } else { throw new InvalidArgumentException( __METHOD__ . ': Invalid UDP specification' ); diff --git a/includes/libs/composer/ComposerInstalled.php b/includes/libs/composer/ComposerInstalled.php index ef2b768d0b..54d43d37cd 100644 --- a/includes/libs/composer/ComposerInstalled.php +++ b/includes/libs/composer/ComposerInstalled.php @@ -26,9 +26,9 @@ class ComposerInstalled { $deps[$installed['name']] = [ 'version' => ComposerJson::normalizeVersion( $installed['version'] ), 'type' => $installed['type'], - 'licenses' => isset( $installed['license'] ) ? $installed['license'] : [], - 'authors' => isset( $installed['authors'] ) ? $installed['authors'] : [], - 'description' => isset( $installed['description'] ) ? $installed['description'] : '', + 'licenses' => $installed['license'] ?? [], + 'authors' => $installed['authors'] ?? [], + 'description' => $installed['description'] ?? '', ]; } diff --git a/includes/libs/composer/ComposerLock.php b/includes/libs/composer/ComposerLock.php index dc8bc035b2..c5b5f0040d 100644 --- a/includes/libs/composer/ComposerLock.php +++ b/includes/libs/composer/ComposerLock.php @@ -26,9 +26,9 @@ class ComposerLock { $deps[$installed['name']] = [ 'version' => ComposerJson::normalizeVersion( $installed['version'] ), 'type' => $installed['type'], - 'licenses' => isset( $installed['license'] ) ? $installed['license'] : [], - 'authors' => isset( $installed['authors'] ) ? $installed['authors'] : [], - 'description' => isset( $installed['description'] ) ? $installed['description'] : '', + 'licenses' => $installed['license'] ?? [], + 'authors' => $installed['authors'] ?? [], + 'description' => $installed['description'] ?? '', ]; } diff --git a/includes/libs/filebackend/FSFileBackend.php b/includes/libs/filebackend/FSFileBackend.php index d60e768f86..c2c3b479a2 100644 --- a/includes/libs/filebackend/FSFileBackend.php +++ b/includes/libs/filebackend/FSFileBackend.php @@ -89,8 +89,8 @@ class FSFileBackend extends FileBackendStore { } } - $this->fileMode = isset( $config['fileMode'] ) ? $config['fileMode'] : 0644; - $this->dirMode = isset( $config['directoryMode'] ) ? $config['directoryMode'] : 0777; + $this->fileMode = $config['fileMode'] ?? 0644; + $this->dirMode = $config['directoryMode'] ?? 0777; if ( isset( $config['fileOwner'] ) && function_exists( 'posix_getuid' ) ) { $this->fileOwner = $config['fileOwner']; // cache this, assuming it doesn't change diff --git a/includes/libs/filebackend/FileBackend.php b/includes/libs/filebackend/FileBackend.php index 08f960a646..2d4a772b7e 100644 --- a/includes/libs/filebackend/FileBackend.php +++ b/includes/libs/filebackend/FileBackend.php @@ -170,12 +170,9 @@ abstract class FileBackend implements LoggerAwareInterface { throw new InvalidArgumentException( "Backend domain ID not provided for '{$this->name}'." ); } - $this->lockManager = isset( $config['lockManager'] ) - ? $config['lockManager'] - : new NullLockManager( [] ); - $this->fileJournal = isset( $config['fileJournal'] ) - ? $config['fileJournal'] - : FileJournal::factory( [ 'class' => NullFileJournal::class ], $this->name ); + $this->lockManager = $config['lockManager'] ?? new NullLockManager( [] ); + $this->fileJournal = $config['fileJournal'] + ?? FileJournal::factory( [ 'class' => NullFileJournal::class ], $this->name ); $this->readOnly = isset( $config['readOnly'] ) ? (string)$config['readOnly'] : ''; @@ -185,18 +182,14 @@ abstract class FileBackend implements LoggerAwareInterface { $this->concurrency = isset( $config['concurrency'] ) ? (int)$config['concurrency'] : 50; - $this->obResetFunc = isset( $config['obResetFunc'] ) - ? $config['obResetFunc'] - : [ $this, 'resetOutputBuffer' ]; - $this->streamMimeFunc = isset( $config['streamMimeFunc'] ) - ? $config['streamMimeFunc'] - : null; - $this->statusWrapper = isset( $config['statusWrapper'] ) ? $config['statusWrapper'] : null; - - $this->profiler = isset( $config['profiler'] ) ? $config['profiler'] : null; - $this->logger = isset( $config['logger'] ) ? $config['logger'] : new \Psr\Log\NullLogger(); - $this->statusWrapper = isset( $config['statusWrapper'] ) ? $config['statusWrapper'] : null; - $this->tmpDirectory = isset( $config['tmpDirectory'] ) ? $config['tmpDirectory'] : null; + $this->obResetFunc = $config['obResetFunc'] ?? [ $this, 'resetOutputBuffer' ]; + $this->streamMimeFunc = $config['streamMimeFunc'] ?? null; + $this->statusWrapper = $config['statusWrapper'] ?? null; + + $this->profiler = $config['profiler'] ?? null; + $this->logger = $config['logger'] ?? new \Psr\Log\NullLogger(); + $this->statusWrapper = $config['statusWrapper'] ?? null; + $this->tmpDirectory = $config['tmpDirectory'] ?? null; } public function setLogger( LoggerInterface $logger ) { @@ -1414,7 +1407,7 @@ abstract class FileBackend implements LoggerAwareInterface { */ protected function resolveFSFileObjects( array $ops ) { foreach ( $ops as &$op ) { - $src = isset( $op['src'] ) ? $op['src'] : null; + $src = $op['src'] ?? null; if ( $src instanceof FSFile ) { $op['srcRef'] = $src; $op['src'] = $src->getPath(); diff --git a/includes/libs/filebackend/FileBackendMultiWrite.php b/includes/libs/filebackend/FileBackendMultiWrite.php index 9c367af5ad..655a71048c 100644 --- a/includes/libs/filebackend/FileBackendMultiWrite.php +++ b/includes/libs/filebackend/FileBackendMultiWrite.php @@ -95,12 +95,8 @@ class FileBackendMultiWrite extends FileBackend { */ public function __construct( array $config ) { parent::__construct( $config ); - $this->syncChecks = isset( $config['syncChecks'] ) - ? $config['syncChecks'] - : self::CHECK_SIZE; - $this->autoResync = isset( $config['autoResync'] ) - ? $config['autoResync'] - : false; + $this->syncChecks = $config['syncChecks'] ?? self::CHECK_SIZE; + $this->autoResync = $config['autoResync'] ?? false; $this->asyncWrites = isset( $config['replication'] ) && $config['replication'] === 'async'; // Construct backends here rather than via registration // to keep these backends hidden from outside the proxy. diff --git a/includes/libs/filebackend/FileBackendStore.php b/includes/libs/filebackend/FileBackendStore.php index 16ea3ea497..6c1dc53f34 100644 --- a/includes/libs/filebackend/FileBackendStore.php +++ b/includes/libs/filebackend/FileBackendStore.php @@ -70,9 +70,7 @@ abstract class FileBackendStore extends FileBackend { */ public function __construct( array $config ) { parent::__construct( $config ); - $this->mimeCallback = isset( $config['mimeCallback'] ) - ? $config['mimeCallback'] - : null; + $this->mimeCallback = $config['mimeCallback'] ?? null; $this->srvCache = new EmptyBagOStuff(); // disabled by default $this->memCache = WANObjectCache::newEmpty(); // disabled by default $this->cheapCache = new ProcessCacheLRU( self::CACHE_CHEAP_SIZE ); @@ -649,7 +647,7 @@ abstract class FileBackendStore extends FileBackend { $stat = $this->doGetFileStat( $params ); if ( is_array( $stat ) ) { // file exists // Strongly consistent backends can automatically set "latest" - $stat['latest'] = isset( $stat['latest'] ) ? $stat['latest'] : $latest; + $stat['latest'] = $stat['latest'] ?? $latest; $this->cheapCache->set( $path, 'stat', $stat ); $this->setFileCache( $path, $stat ); // update persistent cache if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata @@ -851,8 +849,8 @@ abstract class FileBackendStore extends FileBackend { $status = $this->newStatus(); // Always set some fields for subclass convenience - $params['options'] = isset( $params['options'] ) ? $params['options'] : []; - $params['headers'] = isset( $params['headers'] ) ? $params['headers'] : []; + $params['options'] = $params['options'] ?? []; + $params['headers'] = $params['headers'] ?? []; // Don't stream it out as text/html if there was a PHP error if ( ( empty( $params['headless'] ) || $params['headers'] ) && headers_sent() ) { @@ -1324,7 +1322,7 @@ abstract class FileBackendStore extends FileBackend { } if ( is_array( $stat ) ) { // file exists // Strongly consistent backends can automatically set "latest" - $stat['latest'] = isset( $stat['latest'] ) ? $stat['latest'] : $latest; + $stat['latest'] = $stat['latest'] ?? $latest; $this->cheapCache->set( $path, 'stat', $stat ); $this->setFileCache( $path, $stat ); // update persistent cache if ( isset( $stat['sha1'] ) ) { // some backends store SHA-1 as metadata diff --git a/includes/libs/filebackend/FileOpBatch.php b/includes/libs/filebackend/FileOpBatch.php index 2324098dc2..540961edd1 100644 --- a/includes/libs/filebackend/FileOpBatch.php +++ b/includes/libs/filebackend/FileOpBatch.php @@ -66,7 +66,7 @@ class FileOpBatch { $batchId = $journal->getTimestampedUUID(); $ignoreErrors = !empty( $opts['force'] ); $journaled = empty( $opts['nonJournaled'] ); - $maxConcurrency = isset( $opts['concurrency'] ) ? $opts['concurrency'] : 1; + $maxConcurrency = $opts['concurrency'] ?? 1; $entries = []; // file journal entry list $predicates = FileOp::newPredicates(); // account for previous ops in prechecks diff --git a/includes/libs/filebackend/HTTPFileStreamer.php b/includes/libs/filebackend/HTTPFileStreamer.php index 46cd6befd9..e1612546d6 100644 --- a/includes/libs/filebackend/HTTPFileStreamer.php +++ b/includes/libs/filebackend/HTTPFileStreamer.php @@ -47,12 +47,8 @@ class HTTPFileStreamer { */ public function __construct( $path, array $params = [] ) { $this->path = $path; - $this->obResetFunc = isset( $params['obResetFunc'] ) - ? $params['obResetFunc'] - : [ __CLASS__, 'resetOutputBuffers' ]; - $this->streamMimeFunc = isset( $params['streamMimeFunc'] ) - ? $params['streamMimeFunc'] - : [ __CLASS__, 'contentTypeFromPath' ]; + $this->obResetFunc = $params['obResetFunc'] ?? [ __CLASS__, 'resetOutputBuffers' ]; + $this->streamMimeFunc = $params['streamMimeFunc'] ?? [ __CLASS__, 'contentTypeFromPath' ]; } /** diff --git a/includes/libs/filebackend/SwiftFileBackend.php b/includes/libs/filebackend/SwiftFileBackend.php index 997974e7f2..3cd973ea48 100644 --- a/includes/libs/filebackend/SwiftFileBackend.php +++ b/includes/libs/filebackend/SwiftFileBackend.php @@ -116,24 +116,12 @@ class SwiftFileBackend extends FileBackendStore { $this->swiftUser = $config['swiftUser']; $this->swiftKey = $config['swiftKey']; // Optional settings - $this->authTTL = isset( $config['swiftAuthTTL'] ) - ? $config['swiftAuthTTL'] - : 15 * 60; // some sane number - $this->swiftTempUrlKey = isset( $config['swiftTempUrlKey'] ) - ? $config['swiftTempUrlKey'] - : ''; - $this->swiftStorageUrl = isset( $config['swiftStorageUrl'] ) - ? $config['swiftStorageUrl'] - : null; - $this->shardViaHashLevels = isset( $config['shardViaHashLevels'] ) - ? $config['shardViaHashLevels'] - : ''; - $this->rgwS3AccessKey = isset( $config['rgwS3AccessKey'] ) - ? $config['rgwS3AccessKey'] - : ''; - $this->rgwS3SecretKey = isset( $config['rgwS3SecretKey'] ) - ? $config['rgwS3SecretKey'] - : ''; + $this->authTTL = $config['swiftAuthTTL'] ?? 15 * 60; // some sane number + $this->swiftTempUrlKey = $config['swiftTempUrlKey'] ?? ''; + $this->swiftStorageUrl = $config['swiftStorageUrl'] ?? null; + $this->shardViaHashLevels = $config['shardViaHashLevels'] ?? ''; + $this->rgwS3AccessKey = $config['rgwS3AccessKey'] ?? ''; + $this->rgwS3SecretKey = $config['rgwS3SecretKey'] ?? ''; // HTTP helper client $this->http = new MultiHttpClient( [] ); // Cache container information to mask latency @@ -148,18 +136,10 @@ class SwiftFileBackend extends FileBackendStore { } else { $this->srvCache = new EmptyBagOStuff(); } - $this->readUsers = isset( $config['readUsers'] ) - ? $config['readUsers'] - : []; - $this->writeUsers = isset( $config['writeUsers'] ) - ? $config['writeUsers'] - : []; - $this->secureReadUsers = isset( $config['secureReadUsers'] ) - ? $config['secureReadUsers'] - : []; - $this->secureWriteUsers = isset( $config['secureWriteUsers'] ) - ? $config['secureWriteUsers'] - : []; + $this->readUsers = $config['readUsers'] ?? []; + $this->writeUsers = $config['writeUsers'] ?? []; + $this->secureReadUsers = $config['secureReadUsers'] ?? []; + $this->secureWriteUsers = $config['secureWriteUsers'] ?? []; } public function getFeatures() { @@ -299,9 +279,8 @@ class SwiftFileBackend extends FileBackendStore { } $sha1Hash = Wikimedia\base_convert( sha1( $params['content'] ), 16, 36, 31 ); - $contentType = isset( $params['headers']['content-type'] ) - ? $params['headers']['content-type'] - : $this->getContentType( $params['dst'], $params['content'], null ); + $contentType = $params['headers']['content-type'] + ?? $this->getContentType( $params['dst'], $params['content'], null ); $reqs = [ [ 'method' => 'PUT', @@ -356,9 +335,8 @@ class SwiftFileBackend extends FileBackendStore { return $status; } $sha1Hash = Wikimedia\base_convert( $sha1Hash, 16, 36, 31 ); - $contentType = isset( $params['headers']['content-type'] ) - ? $params['headers']['content-type'] - : $this->getContentType( $params['dst'], null, $params['src'] ); + $contentType = $params['headers']['content-type'] + ?? $this->getContentType( $params['dst'], null, $params['src'] ); $handle = fopen( $params['src'], 'rb' ); if ( $handle === false ) { // source doesn't exist? @@ -1237,7 +1215,7 @@ class SwiftFileBackend extends FileBackendStore { return null; } - $ttl = isset( $params['ttl'] ) ? $params['ttl'] : 86400; + $ttl = $params['ttl'] ?? 86400; $expires = time() + $ttl; if ( $this->swiftTempUrlKey != '' ) { @@ -1325,7 +1303,7 @@ class SwiftFileBackend extends FileBackendStore { foreach ( $reqs as $stage => &$req ) { list( $container, $relPath ) = $req['url']; $req['url'] = $this->storageUrl( $auth, $container, $relPath ); - $req['headers'] = isset( $req['headers'] ) ? $req['headers'] : []; + $req['headers'] = $req['headers'] ?? []; $req['headers'] = $this->authTokenHeaders( $auth ) + $req['headers']; $httpReqsByStage[$stage][$index] = $req; } @@ -1686,7 +1664,7 @@ class SwiftFileBackend extends FileBackendStore { 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW ), // Empty objects actually return no content-length header in Ceph 'size' => isset( $rhdrs['content-length'] ) ? (int)$rhdrs['content-length'] : 0, - 'sha1' => isset( $metadata['sha1base36'] ) ? $metadata['sha1base36'] : null, + 'sha1' => $metadata['sha1base36'] ?? null, // Note: manifiest ETags are not an MD5 of the file 'md5' => ctype_xdigit( $rhdrs['etag'] ) ? $rhdrs['etag'] : null, 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ] diff --git a/includes/libs/filebackend/filejournal/FileJournal.php b/includes/libs/filebackend/filejournal/FileJournal.php index 5ba59c5c97..9343fcce07 100644 --- a/includes/libs/filebackend/filejournal/FileJournal.php +++ b/includes/libs/filebackend/filejournal/FileJournal.php @@ -48,7 +48,7 @@ abstract class FileJournal { * 'ttlDays' : days to keep log entries around (false means "forever") */ protected function __construct( array $config ) { - $this->ttlDays = isset( $config['ttlDays'] ) ? $config['ttlDays'] : false; + $this->ttlDays = $config['ttlDays'] ?? false; } /** diff --git a/includes/libs/filebackend/fileop/FileOp.php b/includes/libs/filebackend/fileop/FileOp.php index 40af7aca78..211928973d 100644 --- a/includes/libs/filebackend/fileop/FileOp.php +++ b/includes/libs/filebackend/fileop/FileOp.php @@ -137,7 +137,7 @@ abstract class FileOp { * @return mixed Returns null if the parameter is not set */ final public function getParam( $name ) { - return isset( $this->params[$name] ) ? $this->params[$name] : null; + return $this->params[$name] ?? null; } /** diff --git a/includes/libs/lockmanager/DBLockManager.php b/includes/libs/lockmanager/DBLockManager.php index 26e25f9305..564616dd97 100644 --- a/includes/libs/lockmanager/DBLockManager.php +++ b/includes/libs/lockmanager/DBLockManager.php @@ -90,9 +90,7 @@ abstract class DBLockManager extends QuorumLockManager { // Tracks peers that couldn't be queried recently to avoid lengthy // connection timeouts. This is useless if each bucket has one peer. - $this->statusCache = isset( $config['srvCache'] ) - ? $config['srvCache'] - : new HashBagOStuff(); + $this->statusCache = $config['srvCache'] ?? new HashBagOStuff(); } /** diff --git a/includes/libs/lockmanager/LockManager.php b/includes/libs/lockmanager/LockManager.php index 6b3cfb44ae..e310768f03 100644 --- a/includes/libs/lockmanager/LockManager.php +++ b/includes/libs/lockmanager/LockManager.php @@ -80,7 +80,7 @@ abstract class LockManager { * This only applies if locks are not tied to a connection/process. */ public function __construct( array $config ) { - $this->domain = isset( $config['domain'] ) ? $config['domain'] : 'global'; + $this->domain = $config['domain'] ?? 'global'; if ( isset( $config['lockTTL'] ) ) { $this->lockTTL = max( 5, $config['lockTTL'] ); } elseif ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ) { @@ -101,7 +101,7 @@ abstract class LockManager { } $this->session = md5( implode( '-', $random ) ); - $this->logger = isset( $config['logger'] ) ? $config['logger'] : new \Psr\Log\NullLogger(); + $this->logger = $config['logger'] ?? new \Psr\Log\NullLogger(); } /** diff --git a/includes/libs/lockmanager/MemcLockManager.php b/includes/libs/lockmanager/MemcLockManager.php index 6274d60518..ebd72de894 100644 --- a/includes/libs/lockmanager/MemcLockManager.php +++ b/includes/libs/lockmanager/MemcLockManager.php @@ -68,7 +68,7 @@ class MemcLockManager extends QuorumLockManager { $this->srvsByBucket = array_filter( $config['srvsByBucket'], 'is_array' ); $this->srvsByBucket = array_values( $this->srvsByBucket ); // consecutive - $memcConfig = isset( $config['memcConfig'] ) ? $config['memcConfig'] : []; + $memcConfig = $config['memcConfig'] ?? []; $memcConfig += [ 'class' => MemcachedPhpBagOStuff::class ]; // default $class = $memcConfig['class']; diff --git a/includes/libs/mime/MimeAnalyzer.php b/includes/libs/mime/MimeAnalyzer.php index 8d842cbb7b..4a16679ec3 100644 --- a/includes/libs/mime/MimeAnalyzer.php +++ b/includes/libs/mime/MimeAnalyzer.php @@ -195,21 +195,11 @@ EOT; $this->typeFile = $params['typeFile']; $this->infoFile = $params['infoFile']; $this->xmlTypes = $params['xmlTypes']; - $this->initCallback = isset( $params['initCallback'] ) - ? $params['initCallback'] - : null; - $this->detectCallback = isset( $params['detectCallback'] ) - ? $params['detectCallback'] - : null; - $this->guessCallback = isset( $params['guessCallback'] ) - ? $params['guessCallback'] - : null; - $this->extCallback = isset( $params['extCallback'] ) - ? $params['extCallback'] - : null; - $this->logger = isset( $params['logger'] ) - ? $params['logger'] - : new \Psr\Log\NullLogger(); + $this->initCallback = $params['initCallback'] ?? null; + $this->detectCallback = $params['detectCallback'] ?? null; + $this->guessCallback = $params['guessCallback'] ?? null; + $this->extCallback = $params['extCallback'] ?? null; + $this->logger = $params['logger'] ?? new \Psr\Log\NullLogger(); $this->loadFiles(); } @@ -437,7 +427,7 @@ EOT; public function getTypesForExtension( $ext ) { $ext = strtolower( $ext ); - $r = isset( $this->mExtToMime[$ext] ) ? $this->mExtToMime[$ext] : null; + $r = $this->mExtToMime[$ext] ?? null; return $r; } diff --git a/includes/libs/mime/XmlTypeCheck.php b/includes/libs/mime/XmlTypeCheck.php index 9770515ec0..e231113470 100644 --- a/includes/libs/mime/XmlTypeCheck.php +++ b/includes/libs/mime/XmlTypeCheck.php @@ -394,8 +394,8 @@ class XmlTypeCheck { $callbackReturn = call_user_func( $externalCallback, $parsedDTD['type'], - isset( $parsedDTD['publicid'] ) ? $parsedDTD['publicid'] : null, - isset( $parsedDTD['systemid'] ) ? $parsedDTD['systemid'] : null + $parsedDTD['publicid'] ?? null, + $parsedDTD['systemid'] ?? null ); } if ( $callbackReturn ) { diff --git a/includes/libs/objectcache/BagOStuff.php b/includes/libs/objectcache/BagOStuff.php index 8a88581026..424d986d35 100644 --- a/includes/libs/objectcache/BagOStuff.php +++ b/includes/libs/objectcache/BagOStuff.php @@ -119,15 +119,13 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface { $this->keyspace = $params['keyspace']; } - $this->asyncHandler = isset( $params['asyncHandler'] ) - ? $params['asyncHandler'] - : null; + $this->asyncHandler = $params['asyncHandler'] ?? null; if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler ) ) { $this->reportDupes = true; } - $this->syncTimeout = isset( $params['syncTimeout'] ) ? $params['syncTimeout'] : 3; + $this->syncTimeout = $params['syncTimeout'] ?? 3; } /** @@ -784,7 +782,7 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface { * @since 1.28 */ public function getQoS( $flag ) { - return isset( $this->attrMap[$flag] ) ? $this->attrMap[$flag] : self::QOS_UNKNOWN; + return $this->attrMap[$flag] ?? self::QOS_UNKNOWN; } /** diff --git a/includes/libs/objectcache/HashBagOStuff.php b/includes/libs/objectcache/HashBagOStuff.php index f8e3b17a8c..0d36f4d903 100644 --- a/includes/libs/objectcache/HashBagOStuff.php +++ b/includes/libs/objectcache/HashBagOStuff.php @@ -44,7 +44,7 @@ class HashBagOStuff extends BagOStuff { function __construct( $params = [] ) { parent::__construct( $params ); - $this->maxCacheKeys = isset( $params['maxKeys'] ) ? $params['maxKeys'] : INF; + $this->maxCacheKeys = $params['maxKeys'] ?? INF; if ( $this->maxCacheKeys <= 0 ) { throw new InvalidArgumentException( '$maxKeys parameter must be above zero' ); } diff --git a/includes/libs/objectcache/MemcachedClient.php b/includes/libs/objectcache/MemcachedClient.php index 59131b976a..1cc07b71ef 100644 --- a/includes/libs/objectcache/MemcachedClient.php +++ b/includes/libs/objectcache/MemcachedClient.php @@ -259,11 +259,11 @@ class MemcachedClient { * @return mixed */ public function __construct( $args ) { - $this->set_servers( isset( $args['servers'] ) ? $args['servers'] : array() ); - $this->_debug = isset( $args['debug'] ) ? $args['debug'] : false; + $this->set_servers( $args['servers'] ?? array() ); + $this->_debug = $args['debug'] ?? false; $this->stats = array(); - $this->_compress_threshold = isset( $args['compress_threshold'] ) ? $args['compress_threshold'] : 0; - $this->_persistent = isset( $args['persistent'] ) ? $args['persistent'] : false; + $this->_compress_threshold = $args['compress_threshold'] ?? 0; + $this->_persistent = $args['persistent'] ?? false; $this->_compress_enable = true; $this->_have_zlib = function_exists( 'gzcompress' ); @@ -271,12 +271,12 @@ class MemcachedClient { $this->_host_dead = array(); $this->_timeout_seconds = 0; - $this->_timeout_microseconds = isset( $args['timeout'] ) ? $args['timeout'] : 500000; + $this->_timeout_microseconds = $args['timeout'] ?? 500000; - $this->_connect_timeout = isset( $args['connect_timeout'] ) ? $args['connect_timeout'] : 0.1; + $this->_connect_timeout = $args['connect_timeout'] ?? 0.1; $this->_connect_attempts = 2; - $this->_logger = isset( $args['logger'] ) ? $args['logger'] : new NullLogger(); + $this->_logger = $args['logger'] ?? new NullLogger(); } // }}} diff --git a/includes/libs/objectcache/RedisBagOStuff.php b/includes/libs/objectcache/RedisBagOStuff.php index f720010f41..432e6d65cb 100644 --- a/includes/libs/objectcache/RedisBagOStuff.php +++ b/includes/libs/objectcache/RedisBagOStuff.php @@ -396,9 +396,7 @@ class RedisBagOStuff extends BagOStuff { */ protected function getMasterLinkStatus( RedisConnRef $conn ) { $info = $conn->info(); - return isset( $info['master_link_status'] ) - ? $info['master_link_status'] - : null; + return $info['master_link_status'] ?? null; } /** diff --git a/includes/libs/objectcache/WANObjectCache.php b/includes/libs/objectcache/WANObjectCache.php index 17f596d6b8..9bdb286966 100644 --- a/includes/libs/objectcache/WANObjectCache.php +++ b/includes/libs/objectcache/WANObjectCache.php @@ -223,19 +223,15 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface { */ public function __construct( array $params ) { $this->cache = $params['cache']; - $this->purgeChannel = isset( $params['channels']['purge'] ) - ? $params['channels']['purge'] - : self::DEFAULT_PURGE_CHANNEL; - $this->purgeRelayer = isset( $params['relayers']['purge'] ) - ? $params['relayers']['purge'] - : new EventRelayerNull( [] ); - $this->region = isset( $params['region'] ) ? $params['region'] : 'main'; - $this->cluster = isset( $params['cluster'] ) ? $params['cluster'] : 'wan-main'; + $this->purgeChannel = $params['channels']['purge'] ?? self::DEFAULT_PURGE_CHANNEL; + $this->purgeRelayer = $params['relayers']['purge'] ?? new EventRelayerNull( [] ); + $this->region = $params['region'] ?? 'main'; + $this->cluster = $params['cluster'] ?? 'wan-main'; $this->mcrouterAware = !empty( $params['mcrouterAware'] ); - $this->setLogger( isset( $params['logger'] ) ? $params['logger'] : new NullLogger() ); - $this->stats = isset( $params['stats'] ) ? $params['stats'] : new NullStatsdDataFactory(); - $this->asyncHandler = isset( $params['asyncHandler'] ) ? $params['asyncHandler'] : null; + $this->setLogger( $params['logger'] ?? new NullLogger() ); + $this->stats = $params['stats'] ?? new NullStatsdDataFactory(); + $this->asyncHandler = $params['asyncHandler'] ?? null; } /** @@ -301,10 +297,10 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface { $curTTLs = []; $asOfs = []; $values = $this->getMulti( [ $key ], $curTTLs, $checkKeys, $asOfs ); - $curTTL = isset( $curTTLs[$key] ) ? $curTTLs[$key] : null; - $asOf = isset( $asOfs[$key] ) ? $asOfs[$key] : null; + $curTTL = $curTTLs[$key] ?? null; + $asOf = $asOfs[$key] ?? null; - return isset( $values[$key] ) ? $values[$key] : false; + return $values[$key] ?? false; } /** @@ -494,10 +490,10 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface { */ final public function set( $key, $value, $ttl = 0, array $opts = [] ) { $now = $this->getCurrentTime(); - $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE; - $staleTTL = isset( $opts['staleTTL'] ) ? $opts['staleTTL'] : self::STALE_TTL_NONE; + $lockTSE = $opts['lockTSE'] ?? self::TSE_NONE; + $staleTTL = $opts['staleTTL'] ?? self::STALE_TTL_NONE; $age = isset( $opts['since'] ) ? max( 0, $now - $opts['since'] ) : 0; - $lag = isset( $opts['lag'] ) ? $opts['lag'] : 0; + $lag = $opts['lag'] ?? 0; // Do not cache potentially uncommitted data as it might get rolled back if ( !empty( $opts['pending'] ) ) { @@ -1052,13 +1048,13 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface { * @note Callable type hints are not used to avoid class-autoloading */ final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) { - $pcTTL = isset( $opts['pcTTL'] ) ? $opts['pcTTL'] : self::TTL_UNCACHEABLE; + $pcTTL = $opts['pcTTL'] ?? self::TTL_UNCACHEABLE; // Try the process cache if enabled and the cache callback is not within a cache callback. // Process cache use in nested callbacks is not lag-safe with regard to HOLDOFF_TTL since // the in-memory value is further lagged than the shared one since it uses a blind TTL. if ( $pcTTL >= 0 && $this->callbackDepth == 0 ) { - $group = isset( $opts['pcGroup'] ) ? $opts['pcGroup'] : self::PC_PRIMARY; + $group = $opts['pcGroup'] ?? self::PC_PRIMARY; $procCache = $this->getProcessCache( $group ); $value = $procCache->get( $key ); } else { @@ -1137,15 +1133,15 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface { * @note Callable type hints are not used to avoid class-autoloading */ protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts, &$asOf = null ) { - $lowTTL = isset( $opts['lowTTL'] ) ? $opts['lowTTL'] : min( self::LOW_TTL, $ttl ); - $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE; - $staleTTL = isset( $opts['staleTTL'] ) ? $opts['staleTTL'] : self::STALE_TTL_NONE; - $graceTTL = isset( $opts['graceTTL'] ) ? $opts['graceTTL'] : self::GRACE_TTL_NONE; - $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : []; - $busyValue = isset( $opts['busyValue'] ) ? $opts['busyValue'] : null; - $popWindow = isset( $opts['hotTTR'] ) ? $opts['hotTTR'] : self::HOT_TTR; - $ageNew = isset( $opts['ageNew'] ) ? $opts['ageNew'] : self::AGE_NEW; - $minTime = isset( $opts['minAsOf'] ) ? $opts['minAsOf'] : self::MIN_TIMESTAMP_NONE; + $lowTTL = $opts['lowTTL'] ?? min( self::LOW_TTL, $ttl ); + $lockTSE = $opts['lockTSE'] ?? self::TSE_NONE; + $staleTTL = $opts['staleTTL'] ?? self::STALE_TTL_NONE; + $graceTTL = $opts['graceTTL'] ?? self::GRACE_TTL_NONE; + $checkKeys = $opts['checkKeys'] ?? []; + $busyValue = $opts['busyValue'] ?? null; + $popWindow = $opts['hotTTR'] ?? self::HOT_TTR; + $ageNew = $opts['ageNew'] ?? self::AGE_NEW; + $minTime = $opts['minAsOf'] ?? self::MIN_TIMESTAMP_NONE; $versioned = isset( $opts['version'] ); // Get a collection name to describe this class of key @@ -1381,7 +1377,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface { ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = [] ) { $valueKeys = array_keys( $keyedIds->getArrayCopy() ); - $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : []; + $checkKeys = $opts['checkKeys'] ?? []; // Load required keys into process cache in one go $this->warmupCache = $this->getRawKeysForWarmup( @@ -1476,7 +1472,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface { ) { $idsByValueKey = $keyedIds->getArrayCopy(); $valueKeys = array_keys( $idsByValueKey ); - $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : []; + $checkKeys = $opts['checkKeys'] ?? []; unset( $opts['lockTSE'] ); // incompatible unset( $opts['busyValue'] ); // incompatible @@ -2023,7 +2019,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface { return [ false, null ]; } - $flags = isset( $wrapped[self::FLD_FLAGS] ) ? $wrapped[self::FLD_FLAGS] : 0; + $flags = $wrapped[self::FLD_FLAGS] ?? 0; if ( ( $flags & self::FLG_STALE ) == self::FLG_STALE ) { // Treat as expired, with the cache time as the expiration $age = $now - $wrapped[self::FLD_TIME]; @@ -2061,7 +2057,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface { protected function determineKeyClass( $key ) { $parts = explode( ':', $key ); - return isset( $parts[1] ) ? $parts[1] : $parts[0]; // sanity + return $parts[1] ?? $parts[0]; // sanity } /** @@ -2127,7 +2123,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface { private function getNonProcessCachedKeys( array $keys, array $opts ) { $keysFound = []; if ( isset( $opts['pcTTL'] ) && $opts['pcTTL'] > 0 && $this->callbackDepth == 0 ) { - $pcGroup = isset( $opts['pcGroup'] ) ? $opts['pcGroup'] : self::PC_PRIMARY; + $pcGroup = $opts['pcGroup'] ?? self::PC_PRIMARY; $procCache = $this->getProcessCache( $pcGroup ); foreach ( $keys as $key ) { if ( $procCache->get( $key ) !== false ) { diff --git a/includes/libs/objectcache/WANObjectCacheReaper.php b/includes/libs/objectcache/WANObjectCacheReaper.php index 14737b145a..e4ab95c936 100644 --- a/includes/libs/objectcache/WANObjectCacheReaper.php +++ b/includes/libs/objectcache/WANObjectCacheReaper.php @@ -92,12 +92,8 @@ class WANObjectCacheReaper implements LoggerAwareInterface { throw new UnexpectedValueException( "No channel specified." ); } - $this->initialStartWindow = isset( $params['initialStartWindow'] ) - ? $params['initialStartWindow'] - : 3600; - $this->logger = isset( $params['logger'] ) - ? $params['logger'] - : new NullLogger(); + $this->initialStartWindow = $params['initialStartWindow'] ?? 3600; + $this->logger = $params['logger'] ?? new NullLogger(); } public function setLogger( LoggerInterface $logger ) { diff --git a/includes/libs/rdbms/ChronologyProtector.php b/includes/libs/rdbms/ChronologyProtector.php index 8b21ede813..099f172e7f 100644 --- a/includes/libs/rdbms/ChronologyProtector.php +++ b/includes/libs/rdbms/ChronologyProtector.php @@ -330,7 +330,7 @@ class ChronologyProtector implements LoggerAwareInterface { */ protected function mergePositions( $curValue, array $shutdownPositions, &$cpIndex = null ) { /** @var DBMasterPos[] $curPositions */ - $curPositions = isset( $curValue['positions'] ) ? $curValue['positions'] : []; + $curPositions = $curValue['positions'] ?? []; // Use the newest positions for each DB master foreach ( $shutdownPositions as $db => $pos ) { if ( @@ -342,7 +342,7 @@ class ChronologyProtector implements LoggerAwareInterface { } } - $cpIndex = isset( $curValue['writeIndex'] ) ? $curValue['writeIndex'] : 0; + $cpIndex = $curValue['writeIndex'] ?? 0; return [ 'positions' => $curPositions, diff --git a/includes/libs/rdbms/database/Database.php b/includes/libs/rdbms/database/Database.php index 1f92c47399..16e654fe7c 100644 --- a/includes/libs/rdbms/database/Database.php +++ b/includes/libs/rdbms/database/Database.php @@ -315,9 +315,7 @@ abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAware $this->sessionVars = $params['variables']; - $this->srvCache = isset( $params['srvCache'] ) - ? $params['srvCache'] - : new HashBagOStuff(); + $this->srvCache = $params['srvCache'] ?? new HashBagOStuff(); $this->profiler = $params['profiler']; $this->trxProfiler = $params['trxProfiler']; @@ -420,29 +418,27 @@ abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAware * @since 1.18 */ final public static function factory( $dbType, $p = [], $connect = self::NEW_CONNECTED ) { - $class = self::getClass( $dbType, isset( $p['driver'] ) ? $p['driver'] : null ); + $class = self::getClass( $dbType, $p['driver'] ?? null ); if ( class_exists( $class ) && is_subclass_of( $class, IDatabase::class ) ) { // Resolve some defaults for b/c - $p['host'] = isset( $p['host'] ) ? $p['host'] : false; - $p['user'] = isset( $p['user'] ) ? $p['user'] : false; - $p['password'] = isset( $p['password'] ) ? $p['password'] : false; - $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false; - $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0; - $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : []; - $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : ''; - $p['schema'] = isset( $p['schema'] ) ? $p['schema'] : ''; - $p['cliMode'] = isset( $p['cliMode'] ) - ? $p['cliMode'] - : ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ); - $p['agent'] = isset( $p['agent'] ) ? $p['agent'] : ''; + $p['host'] = $p['host'] ?? false; + $p['user'] = $p['user'] ?? false; + $p['password'] = $p['password'] ?? false; + $p['dbname'] = $p['dbname'] ?? false; + $p['flags'] = $p['flags'] ?? 0; + $p['variables'] = $p['variables'] ?? []; + $p['tablePrefix'] = $p['tablePrefix'] ?? ''; + $p['schema'] = $p['schema'] ?? ''; + $p['cliMode'] = $p['cliMode'] ?? ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ); + $p['agent'] = $p['agent'] ?? ''; if ( !isset( $p['connLogger'] ) ) { $p['connLogger'] = new NullLogger(); } if ( !isset( $p['queryLogger'] ) ) { $p['queryLogger'] = new NullLogger(); } - $p['profiler'] = isset( $p['profiler'] ) ? $p['profiler'] : null; + $p['profiler'] = $p['profiler'] ?? null; if ( !isset( $p['trxProfiler'] ) ) { $p['trxProfiler'] = new TransactionProfiler(); } @@ -1716,7 +1712,7 @@ abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAware if ( isset( $options['LIMIT'] ) ) { $sql = $this->limitResult( $sql, $options['LIMIT'], - isset( $options['OFFSET'] ) ? $options['OFFSET'] : false ); + $options['OFFSET'] ?? false ); } $sql = "$sql $postLimitTail"; @@ -1869,7 +1865,7 @@ abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAware if ( !$var ) { $column = null; } elseif ( count( $var ) == 1 ) { - $column = isset( $var[0] ) ? $var[0] : reset( $var ); + $column = $var[0] ?? reset( $var ); } else { throw new DBUnexpectedError( $this, __METHOD__ . ': got multiple columns.' ); } @@ -2577,9 +2573,7 @@ abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAware * @return string */ protected function indexName( $index ) { - return isset( $this->indexAliases[$index] ) - ? $this->indexAliases[$index] - : $index; + return $this->indexAliases[$index] ?? $index; } public function addQuotes( $s ) { @@ -3132,8 +3126,8 @@ abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAware // $conds. Then union them together (using UNION ALL, because the // product *should* already be distinct). $orderBy = $this->makeOrderBy( $options ); - $limit = isset( $options['LIMIT'] ) ? $options['LIMIT'] : null; - $offset = isset( $options['OFFSET'] ) ? $options['OFFSET'] : false; + $limit = $options['LIMIT'] ?? null; + $offset = $options['OFFSET'] ?? false; $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options ); if ( !$this->unionSupportsOrderAndLimit() ) { unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] ); diff --git a/includes/libs/rdbms/database/DatabaseDomain.php b/includes/libs/rdbms/database/DatabaseDomain.php index ef6600b4fc..602b15cab5 100644 --- a/includes/libs/rdbms/database/DatabaseDomain.php +++ b/includes/libs/rdbms/database/DatabaseDomain.php @@ -182,7 +182,7 @@ class DatabaseDomain { for ( $i = 0; $i < $length; ++$i ) { $char = $encoded[$i]; if ( $char === '?' ) { - $nextChar = isset( $encoded[$i + 1] ) ? $encoded[$i + 1] : null; + $nextChar = $encoded[$i + 1] ?? null; if ( $nextChar === 'h' ) { $decoded .= '-'; ++$i; diff --git a/includes/libs/rdbms/database/DatabaseMssql.php b/includes/libs/rdbms/database/DatabaseMssql.php index 768e0c60c4..fed6f14616 100644 --- a/includes/libs/rdbms/database/DatabaseMssql.php +++ b/includes/libs/rdbms/database/DatabaseMssql.php @@ -1294,9 +1294,7 @@ class DatabaseMssql extends Database { $this->populateColumnCaches(); } - return isset( $this->binaryColumnCache[$tableRaw] ) - ? $this->binaryColumnCache[$tableRaw] - : []; + return $this->binaryColumnCache[$tableRaw] ?? []; } /** @@ -1311,9 +1309,7 @@ class DatabaseMssql extends Database { $this->populateColumnCaches(); } - return isset( $this->bitColumnCache[$tableRaw] ) - ? $this->bitColumnCache[$tableRaw] - : []; + return $this->bitColumnCache[$tableRaw] ?? []; } private function populateColumnCaches() { diff --git a/includes/libs/rdbms/database/DatabaseMysqlBase.php b/includes/libs/rdbms/database/DatabaseMysqlBase.php index 953f63d2ff..78c6d91b4d 100644 --- a/includes/libs/rdbms/database/DatabaseMysqlBase.php +++ b/includes/libs/rdbms/database/DatabaseMysqlBase.php @@ -96,12 +96,8 @@ abstract class DatabaseMysqlBase extends Database { * @param array $params */ function __construct( array $params ) { - $this->lagDetectionMethod = isset( $params['lagDetectionMethod'] ) - ? $params['lagDetectionMethod'] - : 'Seconds_Behind_Master'; - $this->lagDetectionOptions = isset( $params['lagDetectionOptions'] ) - ? $params['lagDetectionOptions'] - : []; + $this->lagDetectionMethod = $params['lagDetectionMethod'] ?? 'Seconds_Behind_Master'; + $this->lagDetectionOptions = $params['lagDetectionOptions'] ?? []; $this->useGTIDs = !empty( $params['useGTIDs' ] ); foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) { $var = "ssl{$name}"; @@ -109,7 +105,7 @@ abstract class DatabaseMysqlBase extends Database { $this->$var = $params[$var]; } } - $this->sqlMode = isset( $params['sqlMode'] ) ? $params['sqlMode'] : ''; + $this->sqlMode = $params['sqlMode'] ?? ''; $this->utf8Mode = !empty( $params['utf8Mode'] ); $this->insertSelectIsSafe = isset( $params['insertSelectIsSafe'] ) ? (bool)$params['insertSelectIsSafe'] : null; diff --git a/includes/libs/rdbms/database/DatabasePostgres.php b/includes/libs/rdbms/database/DatabasePostgres.php index 807d9cc240..a043cd6a89 100644 --- a/includes/libs/rdbms/database/DatabasePostgres.php +++ b/includes/libs/rdbms/database/DatabasePostgres.php @@ -54,10 +54,8 @@ class DatabasePostgres extends Database { * - keywordTableMap : Map of reserved table names to alternative table names to use */ public function __construct( array $params ) { - $this->port = isset( $params['port'] ) ? $params['port'] : false; - $this->keywordTableMap = isset( $params['keywordTableMap'] ) - ? $params['keywordTableMap'] - : []; + $this->port = $params['port'] ?? false; + $this->keywordTableMap = $params['keywordTableMap'] ?? []; parent::__construct( $params ); } @@ -710,7 +708,7 @@ __INDEXATTR__; * @return string Value of $name or remapped name if $name is a reserved keyword */ public function remappedTableName( $name ) { - return isset( $this->keywordTableMap[$name] ) ? $this->keywordTableMap[$name] : $name; + return $this->keywordTableMap[$name] ?? $name; } /** diff --git a/includes/libs/rdbms/database/DatabaseSqlite.php b/includes/libs/rdbms/database/DatabaseSqlite.php index 5f37c1d176..2125c70fd5 100644 --- a/includes/libs/rdbms/database/DatabaseSqlite.php +++ b/includes/libs/rdbms/database/DatabaseSqlite.php @@ -496,7 +496,7 @@ class DatabaseSqlite extends Database { } $e = $this->conn->errorInfo(); - return isset( $e[2] ) ? $e[2] : ''; + return $e[2] ?? ''; } /** diff --git a/includes/libs/rdbms/field/MySQLField.php b/includes/libs/rdbms/field/MySQLField.php index 709c61eb2d..ecaddab03c 100644 --- a/includes/libs/rdbms/field/MySQLField.php +++ b/includes/libs/rdbms/field/MySQLField.php @@ -18,11 +18,11 @@ class MySQLField implements Field { $this->is_multiple = $info->multiple_key; $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple ); $this->type = $info->type; - $this->binary = isset( $info->binary ) ? $info->binary : false; - $this->is_numeric = isset( $info->numeric ) ? $info->numeric : false; - $this->is_blob = isset( $info->blob ) ? $info->blob : false; - $this->is_unsigned = isset( $info->unsigned ) ? $info->unsigned : false; - $this->is_zerofill = isset( $info->zerofill ) ? $info->zerofill : false; + $this->binary = $info->binary ?? false; + $this->is_numeric = $info->numeric ?? false; + $this->is_blob = $info->blob ?? false; + $this->is_unsigned = $info->unsigned ?? false; + $this->is_zerofill = $info->zerofill ?? false; } /** diff --git a/includes/libs/rdbms/lbfactory/LBFactory.php b/includes/libs/rdbms/lbfactory/LBFactory.php index e8ec25083e..2ee3419e2c 100644 --- a/includes/libs/rdbms/lbfactory/LBFactory.php +++ b/includes/libs/rdbms/lbfactory/LBFactory.php @@ -110,44 +110,34 @@ abstract class LBFactory implements ILBFactory { $this->readOnlyReason = $conf['readOnlyReason']; } - $this->srvCache = isset( $conf['srvCache'] ) ? $conf['srvCache'] : new EmptyBagOStuff(); - $this->memStash = isset( $conf['memStash'] ) ? $conf['memStash'] : new EmptyBagOStuff(); - $this->wanCache = isset( $conf['wanCache'] ) - ? $conf['wanCache'] - : WANObjectCache::newEmpty(); + $this->srvCache = $conf['srvCache'] ?? new EmptyBagOStuff(); + $this->memStash = $conf['memStash'] ?? new EmptyBagOStuff(); + $this->wanCache = $conf['wanCache'] ?? WANObjectCache::newEmpty(); foreach ( self::$loggerFields as $key ) { - $this->$key = isset( $conf[$key] ) ? $conf[$key] : new \Psr\Log\NullLogger(); + $this->$key = $conf[$key] ?? new \Psr\Log\NullLogger(); } - $this->errorLogger = isset( $conf['errorLogger'] ) - ? $conf['errorLogger'] - : function ( Exception $e ) { - trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING ); - }; - $this->deprecationLogger = isset( $conf['deprecationLogger'] ) - ? $conf['deprecationLogger'] - : function ( $msg ) { - trigger_error( $msg, E_USER_DEPRECATED ); - }; - - $this->profiler = isset( $conf['profiler'] ) ? $conf['profiler'] : null; - $this->trxProfiler = isset( $conf['trxProfiler'] ) - ? $conf['trxProfiler'] - : new TransactionProfiler(); + $this->errorLogger = $conf['errorLogger'] ?? function ( Exception $e ) { + trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING ); + }; + $this->deprecationLogger = $conf['deprecationLogger'] ?? function ( $msg ) { + trigger_error( $msg, E_USER_DEPRECATED ); + }; + + $this->profiler = $conf['profiler'] ?? null; + $this->trxProfiler = $conf['trxProfiler'] ?? new TransactionProfiler(); $this->requestInfo = [ - 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ? $_SERVER[ 'REMOTE_ADDR' ] : '', - 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '', + 'IPAddress' => $_SERVER[ 'REMOTE_ADDR' ] ?? '', + 'UserAgent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'ChronologyProtection' => 'true', // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals -- library can't use $wgRequest - 'ChronologyPositionIndex' => isset( $_GET['cpPosIndex'] ) ? $_GET['cpPosIndex'] : null + 'ChronologyPositionIndex' => $_GET['cpPosIndex'] ?? null ]; - $this->cliMode = isset( $conf['cliMode'] ) - ? $conf['cliMode'] - : ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ); - $this->hostname = isset( $conf['hostname'] ) ? $conf['hostname'] : gethostname(); - $this->agent = isset( $conf['agent'] ) ? $conf['agent'] : ''; + $this->cliMode = $conf['cliMode'] ?? ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ); + $this->hostname = $conf['hostname'] ?? gethostname(); + $this->agent = $conf['agent'] ?? ''; $this->ticket = mt_rand(); } diff --git a/includes/libs/rdbms/lbfactory/LBFactorySimple.php b/includes/libs/rdbms/lbfactory/LBFactorySimple.php index 9a6aa3a74d..0d7b812da7 100644 --- a/includes/libs/rdbms/lbfactory/LBFactorySimple.php +++ b/includes/libs/rdbms/lbfactory/LBFactorySimple.php @@ -62,7 +62,7 @@ class LBFactorySimple extends LBFactory { public function __construct( array $conf ) { parent::__construct( $conf ); - $this->servers = isset( $conf['servers'] ) ? $conf['servers'] : []; + $this->servers = $conf['servers'] ?? []; foreach ( $this->servers as $i => $server ) { if ( $i == 0 ) { $this->servers[$i]['master'] = true; @@ -71,13 +71,9 @@ class LBFactorySimple extends LBFactory { } } - $this->externalClusters = isset( $conf['externalClusters'] ) - ? $conf['externalClusters'] - : []; - $this->loadMonitorClass = isset( $conf['loadMonitorClass'] ) - ? $conf['loadMonitorClass'] - : 'LoadMonitor'; - $this->maxLag = isset( $conf['maxLag'] ) ? $conf['maxLag'] : self::MAX_LAG_DEFAULT; + $this->externalClusters = $conf['externalClusters'] ?? []; + $this->loadMonitorClass = $conf['loadMonitorClass'] ?? 'LoadMonitor'; + $this->maxLag = $conf['maxLag'] ?? self::MAX_LAG_DEFAULT; } /** diff --git a/includes/libs/rdbms/loadbalancer/LoadBalancer.php b/includes/libs/rdbms/loadbalancer/LoadBalancer.php index eabcbbdb4f..75f8845751 100644 --- a/includes/libs/rdbms/loadbalancer/LoadBalancer.php +++ b/includes/libs/rdbms/loadbalancer/LoadBalancer.php @@ -172,9 +172,7 @@ class LoadBalancer implements ILoadBalancer { : DatabaseDomain::newUnspecified(); $this->setLocalDomain( $localDomain ); - $this->waitTimeout = isset( $params['waitTimeout'] ) - ? $params['waitTimeout'] - : self::MAX_WAIT_DEFAULT; + $this->waitTimeout = $params['waitTimeout'] ?? self::MAX_WAIT_DEFAULT; $this->readIndex = -1; $this->conns = [ @@ -228,35 +226,27 @@ class LoadBalancer implements ILoadBalancer { } else { $this->wanCache = WANObjectCache::newEmpty(); } - $this->profiler = isset( $params['profiler'] ) ? $params['profiler'] : null; + $this->profiler = $params['profiler'] ?? null; if ( isset( $params['trxProfiler'] ) ) { $this->trxProfiler = $params['trxProfiler']; } else { $this->trxProfiler = new TransactionProfiler(); } - $this->errorLogger = isset( $params['errorLogger'] ) - ? $params['errorLogger'] - : function ( Exception $e ) { - trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING ); - }; - $this->deprecationLogger = isset( $params['deprecationLogger'] ) - ? $params['deprecationLogger'] - : function ( $msg ) { - trigger_error( $msg, E_USER_DEPRECATED ); - }; + $this->errorLogger = $params['errorLogger'] ?? function ( Exception $e ) { + trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING ); + }; + $this->deprecationLogger = $params['deprecationLogger'] ?? function ( $msg ) { + trigger_error( $msg, E_USER_DEPRECATED ); + }; foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) { - $this->$key = isset( $params[$key] ) ? $params[$key] : new NullLogger(); + $this->$key = $params[$key] ?? new NullLogger(); } - $this->host = isset( $params['hostname'] ) - ? $params['hostname'] - : ( gethostname() ?: 'unknown' ); - $this->cliMode = isset( $params['cliMode'] ) - ? $params['cliMode'] - : ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ); - $this->agent = isset( $params['agent'] ) ? $params['agent'] : ''; + $this->host = $params['hostname'] ?? ( gethostname() ?: 'unknown' ); + $this->cliMode = $params['cliMode'] ?? ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ); + $this->agent = $params['agent'] ?? ''; if ( isset( $params['chronologyCallback'] ) ) { $this->chronologyCallback = $params['chronologyCallback']; @@ -321,9 +311,7 @@ class LoadBalancer implements ILoadBalancer { foreach ( $lags as $i => $lag ) { if ( $i != 0 ) { # How much lag this server nominally is allowed to have - $maxServerLag = isset( $this->servers[$i]['max lag'] ) - ? $this->servers[$i]['max lag'] - : $this->maxLag; // default + $maxServerLag = $this->servers[$i]['max lag'] ?? $this->maxLag; // default # Constrain that futher by $maxLag argument $maxServerLag = min( $maxServerLag, $maxLag ); @@ -1033,7 +1021,7 @@ class LoadBalancer implements ILoadBalancer { public function getServerAttributes( $i ) { return Database::attributesFromType( $this->getServerType( $i ), - isset( $this->servers[$i]['driver'] ) ? $this->servers[$i]['driver'] : null + $this->servers[$i]['driver'] ?? null ); } @@ -1106,7 +1094,7 @@ class LoadBalancer implements ILoadBalancer { $server['agent'] = $this->agent; // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the // application calls LoadBalancer::commitMasterChanges() before the PHP script completes. - $server['flags'] = isset( $server['flags'] ) ? $server['flags'] : IDatabase::DBO_DEFAULT; + $server['flags'] = $server['flags'] ?? IDatabase::DBO_DEFAULT; // Create a live connection object try { @@ -1196,7 +1184,7 @@ class LoadBalancer implements ILoadBalancer { } public function getServerType( $i ) { - return isset( $this->servers[$i]['type'] ) ? $this->servers[$i]['type'] : 'unknown'; + return $this->servers[$i]['type'] ?? 'unknown'; } public function getMasterPos() { @@ -1297,7 +1285,7 @@ class LoadBalancer implements ILoadBalancer { public function approveMasterChanges( array $options ) { $this->assertTransactionRoundStage( self::ROUND_FINALIZED ); - $limit = isset( $options['maxWriteDuration'] ) ? $options['maxWriteDuration'] : 0; + $limit = $options['maxWriteDuration'] ?? 0; $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $limit ) { diff --git a/includes/libs/rdbms/loadbalancer/LoadBalancerSingle.php b/includes/libs/rdbms/loadbalancer/LoadBalancerSingle.php index d29258f4bb..1b72502b14 100644 --- a/includes/libs/rdbms/loadbalancer/LoadBalancerSingle.php +++ b/includes/libs/rdbms/loadbalancer/LoadBalancerSingle.php @@ -52,9 +52,9 @@ class LoadBalancerSingle extends LoadBalancer { 'load' => 1, ] ], - 'trxProfiler' => isset( $params['trxProfiler'] ) ? $params['trxProfiler'] : null, - 'srvCache' => isset( $params['srvCache'] ) ? $params['srvCache'] : null, - 'wanCache' => isset( $params['wanCache'] ) ? $params['wanCache'] : null + 'trxProfiler' => $params['trxProfiler'] ?? null, + 'srvCache' => $params['srvCache'] ?? null, + 'wanCache' => $params['wanCache'] ?? null ] ); if ( isset( $params['readOnlyReason'] ) ) { diff --git a/includes/libs/rdbms/loadmonitor/LoadMonitor.php b/includes/libs/rdbms/loadmonitor/LoadMonitor.php index c7f807a0bc..01834ee91b 100644 --- a/includes/libs/rdbms/loadmonitor/LoadMonitor.php +++ b/includes/libs/rdbms/loadmonitor/LoadMonitor.php @@ -69,12 +69,8 @@ class LoadMonitor implements ILoadMonitor { $this->wanCache = $wCache; $this->replLogger = new NullLogger(); - $this->movingAveRatio = isset( $options['movingAveRatio'] ) - ? $options['movingAveRatio'] - : 0.1; - $this->lagWarnThreshold = isset( $options['lagWarnThreshold'] ) - ? $options['lagWarnThreshold'] - : self::LAG_WARN_THRESHOLD; + $this->movingAveRatio = $options['movingAveRatio'] ?? 0.1; + $this->lagWarnThreshold = $options['lagWarnThreshold'] ?? self::LAG_WARN_THRESHOLD; } public function setLogger( LoggerInterface $logger ) { @@ -167,9 +163,7 @@ class LoadMonitor implements ILoadMonitor { $close = true; // new connection } - $lastWeight = isset( $staleValue['weightScales'][$i] ) - ? $staleValue['weightScales'][$i] - : 1.0; + $lastWeight = $staleValue['weightScales'][$i] ?? 1.0; $coefficient = $this->getWeightScale( $i, $conn ?: null ); $newWeight = $movAveRatio * $coefficient + ( 1 - $movAveRatio ) * $lastWeight; diff --git a/includes/libs/rdbms/loadmonitor/LoadMonitorMySQL.php b/includes/libs/rdbms/loadmonitor/LoadMonitorMySQL.php index 1fbc117c14..dda980c118 100644 --- a/includes/libs/rdbms/loadmonitor/LoadMonitorMySQL.php +++ b/includes/libs/rdbms/loadmonitor/LoadMonitorMySQL.php @@ -39,9 +39,7 @@ class LoadMonitorMySQL extends LoadMonitor { ) { parent::__construct( $lb, $srvCache, $wCache, $options ); - $this->warmCacheRatio = isset( $options['warmCacheRatio'] ) - ? $options['warmCacheRatio'] - : 0.0; + $this->warmCacheRatio = $options['warmCacheRatio'] ?? 0.0; } protected function getWeightScale( $index, IDatabase $conn = null ) { diff --git a/includes/libs/redis/RedisConnectionPool.php b/includes/libs/redis/RedisConnectionPool.php index 509240f71c..82cc23305e 100644 --- a/includes/libs/redis/RedisConnectionPool.php +++ b/includes/libs/redis/RedisConnectionPool.php @@ -81,9 +81,7 @@ class RedisConnectionPool implements LoggerAwareInterface { __CLASS__ . ' requires a Redis client library. ' . 'See https://www.mediawiki.org/wiki/Redis#Setup' ); } - $this->logger = isset( $options['logger'] ) - ? $options['logger'] - : new \Psr\Log\NullLogger(); + $this->logger = $options['logger'] ?? new \Psr\Log\NullLogger(); $this->connectTimeout = $options['connectTimeout']; $this->readTimeout = $options['readTimeout']; $this->persistent = $options['persistent']; diff --git a/includes/libs/virtualrest/VirtualRESTService.php b/includes/libs/virtualrest/VirtualRESTService.php index 2f160787e1..c7b76b68be 100644 --- a/includes/libs/virtualrest/VirtualRESTService.php +++ b/includes/libs/virtualrest/VirtualRESTService.php @@ -51,7 +51,7 @@ abstract class VirtualRESTService { * @return string The name of the service behind this VRS object. */ public function getName() { - return isset( $this->params['name'] ) ? $this->params['name'] : static::class; + return $this->params['name'] ?? static::class; } /** diff --git a/includes/libs/xmp/XMP.php b/includes/libs/xmp/XMP.php index 6a4d7c42d4..b5d469e9f0 100644 --- a/includes/libs/xmp/XMP.php +++ b/includes/libs/xmp/XMP.php @@ -676,8 +676,7 @@ class XMPReader implements LoggerAwareInterface { list( $ns, $tag ) = explode( ' ', $elm, 2 ); if ( isset( $this->items[$ns][$tag]['validate'] ) ) { $info =& $this->items[$ns][$tag]; - $finalName = isset( $info['map_name'] ) - ? $info['map_name'] : $tag; + $finalName = $info['map_name'] ?? $tag; if ( is_array( $info['validate'] ) ) { $validate = $info['validate']; @@ -742,8 +741,7 @@ class XMPReader implements LoggerAwareInterface { private function endElementModeLi( $elm ) { list( $ns, $tag ) = explode( ' ', $this->curItem[0], 2 ); $info = $this->items[$ns][$tag]; - $finalName = isset( $info['map_name'] ) - ? $info['map_name'] : $tag; + $finalName = $info['map_name'] ?? $tag; array_shift( $this->mode ); @@ -1069,8 +1067,7 @@ class XMPReader implements LoggerAwareInterface { array_unshift( $this->mode, $mode ); array_unshift( $this->curItem, $ns . ' ' . $tag ); if ( $mode === self::MODE_STRUCT ) { - $this->ancestorStruct = isset( $this->items[$ns][$tag]['map_name'] ) - ? $this->items[$ns][$tag]['map_name'] : $tag; + $this->ancestorStruct = $this->items[$ns][$tag]['map_name'] ?? $tag; } if ( $this->charContent !== false ) { // Something weird. @@ -1179,8 +1176,7 @@ class XMPReader implements LoggerAwareInterface { throw new RuntimeException( 'Can not find parent of BAGSTRUCT.' ); } list( $curNS, $curTag ) = explode( ' ', $this->curItem[1] ); - $this->ancestorStruct = isset( $this->items[$curNS][$curTag]['map_name'] ) - ? $this->items[$curNS][$curTag]['map_name'] : $curTag; + $this->ancestorStruct = $this->items[$curNS][$curTag]['map_name'] ?? $curTag; $this->doAttribs( $attribs ); } else { @@ -1392,8 +1388,7 @@ class XMPReader implements LoggerAwareInterface { */ private function saveValue( $ns, $tag, $val ) { $info =& $this->items[$ns][$tag]; - $finalName = isset( $info['map_name'] ) - ? $info['map_name'] : $tag; + $finalName = $info['map_name'] ?? $tag; if ( isset( $info['validate'] ) ) { if ( is_array( $info['validate'] ) ) { $validate = $info['validate']; diff --git a/includes/logging/LogFormatter.php b/includes/logging/LogFormatter.php index 0cf3e6d251..54f2d58806 100644 --- a/includes/logging/LogFormatter.php +++ b/includes/logging/LogFormatter.php @@ -377,7 +377,7 @@ class LogFormatter { // new key (5::duration/6::flags) or old key (0/optional 1) if ( $entry->isLegacy() ) { $rawDuration = $parameters[0]; - $rawFlags = isset( $parameters[1] ) ? $parameters[1] : ''; + $rawFlags = $parameters[1] ?? ''; } else { $rawDuration = $parameters['5::duration']; $rawFlags = $parameters['6::flags']; diff --git a/includes/logging/RightsLogFormatter.php b/includes/logging/RightsLogFormatter.php index 8cdd2afb25..6e527e8487 100644 --- a/includes/logging/RightsLogFormatter.php +++ b/includes/logging/RightsLogFormatter.php @@ -95,7 +95,7 @@ class RightsLogFormatter extends LogFormatter { if ( count( $oldGroups ) ) { $params[3] = [ 'raw' => $this->formatRightsList( $oldGroups, - isset( $allParams['oldmetadata'] ) ? $allParams['oldmetadata'] : [] ) ]; + $allParams['oldmetadata'] ?? [] ) ]; } else { $params[3] = $this->msg( 'rightsnone' )->text(); } @@ -103,7 +103,7 @@ class RightsLogFormatter extends LogFormatter { // Array_values is used here because of T44211 // see use of array_unique in UserrightsPage::doSaveUserGroups on $newGroups. $params[4] = [ 'raw' => $this->formatRightsList( array_values( $newGroups ), - isset( $allParams['newmetadata'] ) ? $allParams['newmetadata'] : [] ) ]; + $allParams['newmetadata'] ?? [] ) ]; } else { $params[4] = $this->msg( 'rightsnone' )->text(); } @@ -181,8 +181,7 @@ class RightsLogFormatter extends LogFormatter { if ( isset( $oldmetadata[$index] ) ) { $result += $oldmetadata[$index]; } - $result['expiry'] = ApiResult::formatExpiry( isset( $result['expiry'] ) ? - $result['expiry'] : null ); + $result['expiry'] = ApiResult::formatExpiry( $result['expiry'] ?? null ); return $result; }, array_keys( $params['4:array:oldgroups'] ) ); @@ -199,8 +198,7 @@ class RightsLogFormatter extends LogFormatter { if ( isset( $newmetadata[$index] ) ) { $result += $newmetadata[$index]; } - $result['expiry'] = ApiResult::formatExpiry( isset( $result['expiry'] ) ? - $result['expiry'] : null ); + $result['expiry'] = ApiResult::formatExpiry( $result['expiry'] ?? null ); return $result; }, array_keys( $params['5:array:newgroups'] ) ); diff --git a/includes/mail/UserMailer.php b/includes/mail/UserMailer.php index bdd4f44874..5d7afd31db 100644 --- a/includes/mail/UserMailer.php +++ b/includes/mail/UserMailer.php @@ -244,10 +244,9 @@ class UserMailer { global $wgSMTP, $wgEnotifMaxRecips, $wgAdditionalMailParams; $mime = null; - $replyto = isset( $options['replyTo'] ) ? $options['replyTo'] : null; - $contentType = isset( $options['contentType'] ) ? - $options['contentType'] : 'text/plain; charset=UTF-8'; - $headers = isset( $options['headers'] ) ? $options['headers'] : []; + $replyto = $options['replyTo'] ?? null; + $contentType = $options['contentType'] ?? 'text/plain; charset=UTF-8'; + $headers = $options['headers'] ?? []; // Allow transformation of content, such as encrypting/signing $error = false; diff --git a/includes/media/BitmapMetadataHandler.php b/includes/media/BitmapMetadataHandler.php index 9e0fc3db36..af1bf59abb 100644 --- a/includes/media/BitmapMetadataHandler.php +++ b/includes/media/BitmapMetadataHandler.php @@ -184,7 +184,7 @@ class BitmapMetadataHandler { } } - $meta->getExif( $filename, isset( $seg['byteOrder'] ) ? $seg['byteOrder'] : 'BE' ); + $meta->getExif( $filename, $seg['byteOrder'] ?? 'BE' ); return $meta->getMetadataArray(); } diff --git a/includes/media/DjVuHandler.php b/includes/media/DjVuHandler.php index 2541e35bc5..14074ef4ec 100644 --- a/includes/media/DjVuHandler.php +++ b/includes/media/DjVuHandler.php @@ -105,7 +105,7 @@ class DjVuHandler extends ImageHandler { * @return bool|string */ public function makeParamString( $params ) { - $page = isset( $params['page'] ) ? $params['page'] : 1; + $page = $params['page'] ?? 1; if ( !isset( $params['width'] ) ) { return false; } diff --git a/includes/media/MediaTransformOutput.php b/includes/media/MediaTransformOutput.php index 3506684a50..4aeaac4b6f 100644 --- a/includes/media/MediaTransformOutput.php +++ b/includes/media/MediaTransformOutput.php @@ -360,9 +360,9 @@ class ThumbnailImage extends MediaTransformOutput { throw new MWException( __METHOD__ . ' called in the old style' ); } - $alt = isset( $options['alt'] ) ? $options['alt'] : ''; + $alt = $options['alt'] ?? ''; - $query = isset( $options['desc-query'] ) ? $options['desc-query'] : ''; + $query = $options['desc-query'] ?? ''; $attribs = [ 'alt' => $alt, @@ -487,8 +487,8 @@ class MediaTransformError extends MediaTransformOutput { class TransformParameterError extends MediaTransformError { function __construct( $params ) { parent::__construct( 'thumbnail_error', - max( isset( $params['width'] ) ? $params['width'] : 0, 120 ), - max( isset( $params['height'] ) ? $params['height'] : 0, 120 ), + max( $params['width'] ?? 0, 120 ), + max( $params['height'] ?? 0, 120 ), wfMessage( 'thumbnail_invalid_params' ) ); } @@ -512,8 +512,8 @@ class TransformTooBigImageAreaError extends MediaTransformError { ); parent::__construct( 'thumbnail_error', - max( isset( $params['width'] ) ? $params['width'] : 0, 120 ), - max( isset( $params['height'] ) ? $params['height'] : 0, 120 ), + max( $params['width'] ?? 0, 120 ), + max( $params['height'] ?? 0, 120 ), $msg ); } diff --git a/includes/media/SvgHandler.php b/includes/media/SvgHandler.php index 9085421af8..a589dbf3fb 100644 --- a/includes/media/SvgHandler.php +++ b/includes/media/SvgHandler.php @@ -201,7 +201,7 @@ class SvgHandler extends ImageHandler { $clientHeight = $params['height']; $physicalWidth = $params['physicalWidth']; $physicalHeight = $params['physicalHeight']; - $lang = isset( $params['lang'] ) ? $params['lang'] : $this->getDefaultRenderLanguage( $image ); + $lang = $params['lang'] ?? $this->getDefaultRenderLanguage( $image ); if ( $flags & self::TRANSFORM_LATER ) { return new ThumbnailImage( $image, $dstUrl, $dstPath, $params ); diff --git a/includes/media/TransformationalImageHandler.php b/includes/media/TransformationalImageHandler.php index 85430d2c23..ea0d61bf1a 100644 --- a/includes/media/TransformationalImageHandler.php +++ b/includes/media/TransformationalImageHandler.php @@ -127,7 +127,7 @@ abstract class TransformationalImageHandler extends ImageHandler { 'mimeType' => $image->getMimeType(), 'dstPath' => $dstPath, 'dstUrl' => $dstUrl, - 'interlace' => isset( $params['interlace'] ) ? $params['interlace'] : false, + 'interlace' => $params['interlace'] ?? false, ]; if ( isset( $params['quality'] ) && $params['quality'] === 'low' ) { diff --git a/includes/objectcache/ObjectCache.php b/includes/objectcache/ObjectCache.php index c384032220..6d76d5ed12 100644 --- a/includes/objectcache/ObjectCache.php +++ b/includes/objectcache/ObjectCache.php @@ -182,13 +182,9 @@ class ObjectCache { } elseif ( isset( $params['class'] ) ) { $class = $params['class']; // Automatically set the 'async' update handler - $params['asyncHandler'] = isset( $params['asyncHandler'] ) - ? $params['asyncHandler'] - : 'DeferredUpdates::addCallableUpdate'; + $params['asyncHandler'] = $params['asyncHandler'] ?? 'DeferredUpdates::addCallableUpdate'; // Enable reportDupes by default - $params['reportDupes'] = isset( $params['reportDupes'] ) - ? $params['reportDupes'] - : true; + $params['reportDupes'] = $params['reportDupes'] ?? true; // Do b/c logic for SqlBagOStuff if ( is_a( $class, SqlBagOStuff::class, true ) ) { if ( isset( $params['server'] ) && !isset( $params['servers'] ) ) { @@ -289,7 +285,7 @@ class ObjectCache { $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache(); if ( $cache instanceof EmptyBagOStuff ) { if ( is_array( $fallback ) ) { - $fallback = isset( $fallback['fallback'] ) ? $fallback['fallback'] : CACHE_NONE; + $fallback = $fallback['fallback'] ?? CACHE_NONE; } $cache = self::getInstance( $fallback ); } diff --git a/includes/objectcache/SqlBagOStuff.php b/includes/objectcache/SqlBagOStuff.php index 8ff14ed788..076f208bf0 100644 --- a/includes/objectcache/SqlBagOStuff.php +++ b/includes/objectcache/SqlBagOStuff.php @@ -117,7 +117,7 @@ class SqlBagOStuff extends BagOStuff { if ( is_string( $tag ) ) { $this->serverTags[$index] = $tag; } else { - $this->serverTags[$index] = isset( $info['host'] ) ? $info['host'] : "#$index"; + $this->serverTags[$index] = $info['host'] ?? "#$index"; } ++$index; } @@ -168,8 +168,8 @@ class SqlBagOStuff extends BagOStuff { if ( $this->serverInfos ) { // Use custom database defined by server connection info $info = $this->serverInfos[$serverIndex]; - $type = isset( $info['type'] ) ? $info['type'] : 'mysql'; - $host = isset( $info['host'] ) ? $info['host'] : '[unknown]'; + $type = $info['type'] ?? 'mysql'; + $host = $info['host'] ?? '[unknown]'; $this->logger->debug( __CLASS__ . ": connecting to $host" ); // Use a blank trx profiler to ignore expections as this is a cache $info['trxProfiler'] = new TransactionProfiler(); diff --git a/includes/page/ImagePage.php b/includes/page/ImagePage.php index ecd21d3c8e..81677d41ce 100644 --- a/includes/page/ImagePage.php +++ b/includes/page/ImagePage.php @@ -1042,9 +1042,8 @@ EOT $option = 0; } - return isset( $wgImageLimits[$option] ) - ? $wgImageLimits[$option] - : [ 800, 600 ]; // if nothing is set, fallback to a hardcoded default + // if nothing is set, fallback to a hardcoded default + return $wgImageLimits[$option] ?? [ 800, 600 ]; } /** diff --git a/includes/page/WikiPage.php b/includes/page/WikiPage.php index cbce884dfc..5c1f92c084 100644 --- a/includes/page/WikiPage.php +++ b/includes/page/WikiPage.php @@ -3311,9 +3311,7 @@ class WikiPage implements Page, IDBAccessObject { } // raise error, when the edit is an edit without a new version - $statusRev = isset( $status->value['revision'] ) - ? $status->value['revision'] - : null; + $statusRev = $status->value['revision'] ?? null; if ( !( $statusRev instanceof Revision ) ) { $resultDetails = [ 'current' => $current ]; return [ [ 'alreadyrolled', diff --git a/includes/pager/IndexPager.php b/includes/pager/IndexPager.php index 6880d588d4..2323142373 100644 --- a/includes/pager/IndexPager.php +++ b/includes/pager/IndexPager.php @@ -381,9 +381,9 @@ abstract class IndexPager extends ContextSource implements Pager { $info = $this->getQueryInfo(); $tables = $info['tables']; $fields = $info['fields']; - $conds = isset( $info['conds'] ) ? $info['conds'] : []; - $options = isset( $info['options'] ) ? $info['options'] : []; - $join_conds = isset( $info['join_conds'] ) ? $info['join_conds'] : []; + $conds = $info['conds'] ?? []; + $options = $info['options'] ?? []; + $join_conds = $info['join_conds'] ?? []; $sortColumns = array_merge( [ $this->mIndexField ], $this->mExtraSortFields ); if ( $descending ) { $options['ORDER BY'] = $sortColumns; diff --git a/includes/pager/TablePager.php b/includes/pager/TablePager.php index 70055da39f..b6d5b94c3c 100644 --- a/includes/pager/TablePager.php +++ b/includes/pager/TablePager.php @@ -188,7 +188,7 @@ abstract class TablePager extends IndexPager { $fieldNames = $this->getFieldNames(); foreach ( $fieldNames as $field => $name ) { - $value = isset( $row->$field ) ? $row->$field : null; + $value = $row->$field ?? null; $formatted = strval( $this->formatValue( $field, $value ) ); if ( $formatted == '' ) { diff --git a/includes/parser/CoreParserFunctions.php b/includes/parser/CoreParserFunctions.php index d408c7fffb..7f6dbe530e 100644 --- a/includes/parser/CoreParserFunctions.php +++ b/includes/parser/CoreParserFunctions.php @@ -1059,7 +1059,7 @@ class CoreParserFunctions { $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) ); $value = trim( $frame->expand( $bits['value'] ) ); if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) { - $value = isset( $m[1] ) ? $m[1] : ''; + $value = $m[1] ?? ''; } $attributes[$name] = $value; } diff --git a/includes/parser/LinkHolderArray.php b/includes/parser/LinkHolderArray.php index 816f7f7912..1d722c2cc3 100644 --- a/includes/parser/LinkHolderArray.php +++ b/includes/parser/LinkHolderArray.php @@ -372,7 +372,7 @@ class LinkHolderArray { foreach ( $entries as $index => $entry ) { $pdbk = $entry['pdbk']; $title = $entry['title']; - $query = isset( $entry['query'] ) ? $entry['query'] : []; + $query = $entry['query'] ?? []; $key = "$ns:$index"; $searchkey = ""; $displayText = $entry['text']; diff --git a/includes/parser/Parser.php b/includes/parser/Parser.php index 0bc1a068c2..8df5b5ba09 100644 --- a/includes/parser/Parser.php +++ b/includes/parser/Parser.php @@ -3566,7 +3566,7 @@ class Parser { if ( is_string( $stuff['text'] ) ) { $text = strtr( $text, "\x7f", "?" ); } - $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title; + $finalTitle = $stuff['finalTitle'] ?? $title; if ( isset( $stuff['deps'] ) ) { foreach ( $stuff['deps'] as $dep ) { $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] ); @@ -4763,7 +4763,7 @@ class Parser { if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) { throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" ); } - $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null; + $oldVal = $this->mTagHooks[$tag] ?? null; $this->mTagHooks[$tag] = $callback; if ( !in_array( $tag, $this->mStripList ) ) { $this->mStripList[] = $tag; @@ -4794,7 +4794,7 @@ class Parser { if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) { throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" ); } - $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null; + $oldVal = $this->mTransparentTagHooks[$tag] ?? null; $this->mTransparentTagHooks[$tag] = $callback; return $oldVal; @@ -4909,8 +4909,7 @@ class Parser { if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) { throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" ); } - $old = isset( $this->mFunctionTagHooks[$tag] ) ? - $this->mFunctionTagHooks[$tag] : null; + $old = $this->mFunctionTagHooks[$tag] ?? null; $this->mFunctionTagHooks[$tag] = [ $callback, $flags ]; if ( !in_array( $tag, $this->mStripList ) ) { @@ -5377,7 +5376,7 @@ class Parser { Hooks::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] ); # Linker does the rest - $time = isset( $options['time'] ) ? $options['time'] : false; + $time = $options['time'] ?? false; $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'], $time, $descQuery, $this->mOptions->getThumbSize() ); diff --git a/includes/parser/ParserOutput.php b/includes/parser/ParserOutput.php index fc366599dd..9ec6cf82b2 100644 --- a/includes/parser/ParserOutput.php +++ b/includes/parser/ParserOutput.php @@ -959,7 +959,7 @@ class ParserOutput extends CacheTime { * @note You need to use getProperties() to check for boolean and null properties. */ public function getProperty( $name ) { - return isset( $this->mProperties[$name] ) ? $this->mProperties[$name] : false; + return $this->mProperties[$name] ?? false; } public function unsetProperty( $name ) { diff --git a/includes/parser/Preprocessor_DOM.php b/includes/parser/Preprocessor_DOM.php index 104cd135e9..d00c40f6ac 100644 --- a/includes/parser/Preprocessor_DOM.php +++ b/includes/parser/Preprocessor_DOM.php @@ -1547,7 +1547,7 @@ class PPFrame_DOM implements PPFrame { if ( $level === false ) { return $this->title->getPrefixedDBkey(); } else { - return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false; + return $this->titleCache[$level] ?? false; } } diff --git a/includes/parser/Preprocessor_Hash.php b/includes/parser/Preprocessor_Hash.php index 8e74380c4d..0326499a7a 100644 --- a/includes/parser/Preprocessor_Hash.php +++ b/includes/parser/Preprocessor_Hash.php @@ -1368,7 +1368,7 @@ class PPFrame_Hash implements PPFrame { if ( $level === false ) { return $this->title->getPrefixedDBkey(); } else { - return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false; + return $this->titleCache[$level] ?? false; } } diff --git a/includes/parser/Sanitizer.php b/includes/parser/Sanitizer.php index 118442db0a..ff543dbb30 100644 --- a/includes/parser/Sanitizer.php +++ b/includes/parser/Sanitizer.php @@ -1706,9 +1706,7 @@ class Sanitizer { */ static function attributeWhitelist( $element ) { $list = self::setupAttributeWhitelist(); - return isset( $list[$element] ) - ? $list[$element] - : []; + return $list[$element] ?? []; } /** diff --git a/includes/password/Pbkdf2Password.php b/includes/password/Pbkdf2Password.php index 4a8831e32f..541fd0e1a2 100644 --- a/includes/password/Pbkdf2Password.php +++ b/includes/password/Pbkdf2Password.php @@ -42,8 +42,7 @@ class Pbkdf2Password extends ParameterizedPassword { } protected function shouldUseHashExtension() { - return isset( $this->config['use-hash-extension'] ) ? - $this->config['use-hash-extension'] : function_exists( 'hash_pbkdf2' ); + return $this->config['use-hash-extension'] ?? function_exists( 'hash_pbkdf2' ); } public function crypt( $password ) { diff --git a/includes/poolcounter/PoolCounterWork.php b/includes/poolcounter/PoolCounterWork.php index a570d78c48..16e439797f 100644 --- a/includes/poolcounter/PoolCounterWork.php +++ b/includes/poolcounter/PoolCounterWork.php @@ -150,9 +150,7 @@ abstract class PoolCounterWork { PoolCounter::QUEUE_FULL => 'pool-queuefull', PoolCounter::TIMEOUT => 'pool-timeout' ]; - $status = Status::newFatal( isset( $errors[$status->value] ) - ? $errors[$status->value] - : 'pool-errorunknown' ); + $status = Status::newFatal( $errors[$status->value] ?? 'pool-errorunknown' ); $this->logError( $status ); return $this->error( $status ); } diff --git a/includes/preferences/DefaultPreferencesFactory.php b/includes/preferences/DefaultPreferencesFactory.php index 62973d916b..0a9e9c864b 100644 --- a/includes/preferences/DefaultPreferencesFactory.php +++ b/includes/preferences/DefaultPreferencesFactory.php @@ -185,9 +185,7 @@ class DefaultPreferencesFactory implements PreferencesFactory { $info['disabled'] = 'disabled'; } $field = HTMLForm::loadInputFromParameters( $name, $info, $dummyForm ); // For validation - $globalDefault = isset( $defaultOptions[$name] ) - ? $defaultOptions[$name] - : null; + $globalDefault = $defaultOptions[$name] ?? null; // If it validates, set it as the default if ( isset( $info['default'] ) ) { @@ -221,7 +219,7 @@ class DefaultPreferencesFactory implements PreferencesFactory { if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) || ( isset( $info['class'] ) && $info['class'] == \HTMLMultiSelectField::class ) ) { $options = HTMLFormField::flattenOptions( $info['options'] ); - $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name; + $prefix = $info['prefix'] ?? $name; $val = []; foreach ( $options as $value ) { @@ -236,7 +234,7 @@ class DefaultPreferencesFactory implements PreferencesFactory { ( isset( $info['class'] ) && $info['class'] == \HTMLCheckMatrix::class ) ) { $columns = HTMLFormField::flattenOptions( $info['columns'] ); $rows = HTMLFormField::flattenOptions( $info['rows'] ); - $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name; + $prefix = $info['prefix'] ?? $name; $val = []; foreach ( $columns as $column ) { diff --git a/includes/profiler/ProfilerXhprof.php b/includes/profiler/ProfilerXhprof.php index 9c9666168f..2f2be4727a 100644 --- a/includes/profiler/ProfilerXhprof.php +++ b/includes/profiler/ProfilerXhprof.php @@ -73,7 +73,7 @@ class ProfilerXhprof extends Profiler { public function __construct( array $params = [] ) { parent::__construct( $params ); - $flags = isset( $params['flags'] ) ? $params['flags'] : 0; + $flags = $params['flags'] ?? 0; $options = isset( $params['exclude'] ) ? [ 'ignored_functions' => $params['exclude'] ] : []; Xhprof::enable( $flags, $options ); diff --git a/includes/profiler/output/ProfilerOutputStats.php b/includes/profiler/output/ProfilerOutputStats.php index bb8655183c..6041ba042d 100644 --- a/includes/profiler/output/ProfilerOutputStats.php +++ b/includes/profiler/output/ProfilerOutputStats.php @@ -38,7 +38,7 @@ class ProfilerOutputStats extends ProfilerOutput { * @param array $stats */ public function log( array $stats ) { - $prefix = isset( $this->params['prefix'] ) ? $this->params['prefix'] : ''; + $prefix = $this->params['prefix'] ?? ''; $contextStats = MediaWikiServices::getInstance()->getStatsdDataFactory(); foreach ( $stats as $stat ) { diff --git a/includes/profiler/output/ProfilerOutputText.php b/includes/profiler/output/ProfilerOutputText.php index db3da3e9eb..e3184dbf8a 100644 --- a/includes/profiler/output/ProfilerOutputText.php +++ b/includes/profiler/output/ProfilerOutputText.php @@ -33,9 +33,7 @@ class ProfilerOutputText extends ProfilerOutput { function __construct( Profiler $collector, array $params ) { parent::__construct( $collector, $params ); - $this->thresholdMs = isset( $params['thresholdMs'] ) - ? $params['thresholdMs'] - : 1.0; + $this->thresholdMs = $params['thresholdMs'] ?? 1.0; } public function log( array $stats ) { if ( $this->collector->getTemplated() ) { @@ -62,8 +60,7 @@ class ProfilerOutputText extends ProfilerOutput { if ( wfIsCLI() ) { print "\n"; } elseif ( $contentType === 'text/html' ) { - $visible = isset( $this->params['visible'] ) ? - $this->params['visible'] : false; + $visible = $this->params['visible'] ?? false; if ( $visible ) { print "
{$out}
"; } else { diff --git a/includes/registration/ExtensionProcessor.php b/includes/registration/ExtensionProcessor.php index 14d4a17daa..a803e3a80d 100644 --- a/includes/registration/ExtensionProcessor.php +++ b/includes/registration/ExtensionProcessor.php @@ -298,7 +298,7 @@ class ExtensionProcessor implements Processor { } public function getRequirements( array $info ) { - return isset( $info['requires'] ) ? $info['requires'] : []; + return $info['requires'] ?? []; } protected function extractHooks( array $info ) { @@ -359,9 +359,7 @@ class ExtensionProcessor implements Processor { } protected function extractResourceLoaderModules( $dir, array $info ) { - $defaultPaths = isset( $info['ResourceFileModulePaths'] ) - ? $info['ResourceFileModulePaths'] - : false; + $defaultPaths = $info['ResourceFileModulePaths'] ?? false; if ( isset( $defaultPaths['localBasePath'] ) ) { if ( $defaultPaths['localBasePath'] === '' ) { // Avoid double slashes (e.g. /extensions/Example//path) @@ -426,7 +424,7 @@ class ExtensionProcessor implements Processor { protected function extractCredits( $path, array $info ) { $credits = [ 'path' => $path, - 'type' => isset( $info['type'] ) ? $info['type'] : 'other', + 'type' => $info['type'] ?? 'other', ]; foreach ( self::$creditsAttributes as $attr ) { if ( isset( $info[$attr] ) ) { diff --git a/includes/resourceloader/ResourceLoader.php b/includes/resourceloader/ResourceLoader.php index f3b6a70c6d..43f294b9c5 100644 --- a/includes/resourceloader/ResourceLoader.php +++ b/includes/resourceloader/ResourceLoader.php @@ -1103,7 +1103,7 @@ MESSAGE; $strContent = isset( $styles['css'] ) ? implode( '', $styles['css'] ) : ''; break; default: - $scripts = isset( $content['scripts'] ) ? $content['scripts'] : ''; + $scripts = $content['scripts'] ?? ''; if ( is_string( $scripts ) ) { if ( $name === 'site' || $name === 'user' ) { // Legacy scripts that run in the global scope without a closure. @@ -1120,9 +1120,9 @@ MESSAGE; $strContent = self::makeLoaderImplementScript( $implementKey, $scripts, - isset( $content['styles'] ) ? $content['styles'] : [], + $content['styles'] ?? [], isset( $content['messagesBlob'] ) ? new XmlJsCode( $content['messagesBlob'] ) : [], - isset( $content['templates'] ) ? $content['templates'] : [] + $content['templates'] ?? [] ); break; } diff --git a/includes/resourceloader/ResourceLoaderFileModule.php b/includes/resourceloader/ResourceLoaderFileModule.php index 7f8c7f53ce..e572aa4169 100644 --- a/includes/resourceloader/ResourceLoaderFileModule.php +++ b/includes/resourceloader/ResourceLoaderFileModule.php @@ -641,7 +641,7 @@ class ResourceLoaderFileModule extends ResourceLoaderModule { $collatedFiles[$default][] = $value; } elseif ( is_array( $value ) ) { // File name as the key, options array as the value - $optionValue = isset( $value[$option] ) ? $value[$option] : $default; + $optionValue = $value[$option] ?? $default; if ( !isset( $collatedFiles[$optionValue] ) ) { $collatedFiles[$optionValue] = []; } diff --git a/includes/resourceloader/ResourceLoaderImageModule.php b/includes/resourceloader/ResourceLoaderImageModule.php index 5e329e84b4..e1bddcc9b9 100644 --- a/includes/resourceloader/ResourceLoaderImageModule.php +++ b/includes/resourceloader/ResourceLoaderImageModule.php @@ -224,7 +224,7 @@ class ResourceLoaderImageModule extends ResourceLoaderModule { public function getImage( $name, ResourceLoaderContext $context ) { $this->loadFromDefinition(); $images = $this->getImages( $context ); - return isset( $images[$name] ) ? $images[$name] : null; + return $images[$name] ?? null; } /** @@ -241,9 +241,7 @@ class ResourceLoaderImageModule extends ResourceLoaderModule { if ( !isset( $this->imageObjects[$skin] ) ) { $this->imageObjects[$skin] = []; if ( !isset( $this->images[$skin] ) ) { - $this->images[$skin] = isset( $this->images['default'] ) ? - $this->images['default'] : - []; + $this->images[$skin] = $this->images['default'] ?? []; } foreach ( $this->images[$skin] as $name => $options ) { $fileDescriptor = is_string( $options ) ? $options : $options['file']; @@ -290,9 +288,7 @@ class ResourceLoaderImageModule extends ResourceLoaderModule { if ( !isset( $this->globalVariants[$skin] ) ) { $this->globalVariants[$skin] = []; if ( !isset( $this->variants[$skin] ) ) { - $this->variants[$skin] = isset( $this->variants['default'] ) ? - $this->variants['default'] : - []; + $this->variants[$skin] = $this->variants['default'] ?? []; } foreach ( $this->variants[$skin] as $name => $config ) { if ( isset( $config['global'] ) && $config['global'] ) { diff --git a/includes/resourceloader/ResourceLoaderOOUIImageModule.php b/includes/resourceloader/ResourceLoaderOOUIImageModule.php index 5c9e1d94ae..313d789249 100644 --- a/includes/resourceloader/ResourceLoaderOOUIImageModule.php +++ b/includes/resourceloader/ResourceLoaderOOUIImageModule.php @@ -35,7 +35,7 @@ class ResourceLoaderOOUIImageModule extends ResourceLoaderImageModule { $themes = self::getSkinThemeMap(); // For backwards-compatibility, allow missing 'themeImages' - $module = isset( $this->definition['themeImages'] ) ? $this->definition['themeImages'] : ''; + $module = $this->definition['themeImages'] ?? ''; $definition = []; foreach ( $themes as $skin => $theme ) { diff --git a/includes/resourceloader/ResourceLoaderWikiModule.php b/includes/resourceloader/ResourceLoaderWikiModule.php index 085244acf3..53ae435d4d 100644 --- a/includes/resourceloader/ResourceLoaderWikiModule.php +++ b/includes/resourceloader/ResourceLoaderWikiModule.php @@ -285,7 +285,7 @@ class ResourceLoaderWikiModule extends ResourceLoaderModule { if ( $options['type'] !== 'style' ) { continue; } - $media = isset( $options['media'] ) ? $options['media'] : 'all'; + $media = $options['media'] ?? 'all'; $style = $this->getContent( $titleText, $context ); if ( strval( $style ) === '' ) { continue; diff --git a/includes/revisiondelete/RevDelList.php b/includes/revisiondelete/RevDelList.php index 89025bc61a..cf895bae89 100644 --- a/includes/revisiondelete/RevDelList.php +++ b/includes/revisiondelete/RevDelList.php @@ -112,7 +112,7 @@ abstract class RevDelList extends RevisionListBase { $bitPars = $params['value']; $comment = $params['comment']; - $perItemStatus = isset( $params['perItemStatus'] ) ? $params['perItemStatus'] : false; + $perItemStatus = $params['perItemStatus'] ?? false; // CAS-style checks are done on the _deleted fields so the select // does not need to use FOR UPDATE nor be in the atomic section @@ -287,7 +287,7 @@ abstract class RevDelList extends RevisionListBase { 'oldBits' => $virtualOldBits, 'comment' => $comment, 'ids' => $idsForLog, - 'tags' => isset( $params['tags'] ) ? $params['tags'] : [], + 'tags' => $params['tags'] ?? [], ] + $authorFields ); diff --git a/includes/services/ServiceContainer.php b/includes/services/ServiceContainer.php index 9f09e22fc4..4c52693a4a 100644 --- a/includes/services/ServiceContainer.php +++ b/includes/services/ServiceContainer.php @@ -185,7 +185,7 @@ class ServiceContainer implements DestructibleService { throw new NoSuchServiceException( $name ); } - return isset( $this->services[$name] ) ? $this->services[$name] : null; + return $this->services[$name] ?? null; } /** diff --git a/includes/session/ImmutableSessionProviderWithCookie.php b/includes/session/ImmutableSessionProviderWithCookie.php index 1cab3d3c0a..200b913389 100644 --- a/includes/session/ImmutableSessionProviderWithCookie.php +++ b/includes/session/ImmutableSessionProviderWithCookie.php @@ -84,9 +84,7 @@ abstract class ImmutableSessionProviderWithCookie extends SessionProvider { ); } - $prefix = isset( $this->sessionCookieOptions['prefix'] ) - ? $this->sessionCookieOptions['prefix'] - : $this->config->get( 'CookiePrefix' ); + $prefix = $this->sessionCookieOptions['prefix'] ?? $this->config->get( 'CookiePrefix' ); $id = $request->getCookie( $this->sessionCookieName, $prefix ); return SessionManager::validateSessionId( $id ) ? $id : null; } @@ -141,9 +139,7 @@ abstract class ImmutableSessionProviderWithCookie extends SessionProvider { return []; } - $prefix = isset( $this->sessionCookieOptions['prefix'] ) - ? $this->sessionCookieOptions['prefix'] - : $this->config->get( 'CookiePrefix' ); + $prefix = $this->sessionCookieOptions['prefix'] ?? $this->config->get( 'CookiePrefix' ); return [ $prefix . $this->sessionCookieName ]; } diff --git a/includes/session/PHPSessionHandler.php b/includes/session/PHPSessionHandler.php index b76f0ff6b7..8787027f8f 100644 --- a/includes/session/PHPSessionHandler.php +++ b/includes/session/PHPSessionHandler.php @@ -283,7 +283,7 @@ class PHPSessionHandler implements \SessionHandlerInterface { // Now merge the data into the Session object. $changed = false; - $cache = isset( $this->sessionFieldCache[$id] ) ? $this->sessionFieldCache[$id] : []; + $cache = $this->sessionFieldCache[$id] ?? []; foreach ( $data as $key => $value ) { if ( !array_key_exists( $key, $cache ) ) { if ( $session->exists( $key ) ) { diff --git a/includes/session/SessionManager.php b/includes/session/SessionManager.php index 603985f50b..ceb9ceb5c7 100644 --- a/includes/session/SessionManager.php +++ b/includes/session/SessionManager.php @@ -455,7 +455,7 @@ final class SessionManager implements SessionManagerInterface { */ public function getProvider( $name ) { $providers = $this->getProviders(); - return isset( $providers[$name] ) ? $providers[$name] : null; + return $providers[$name] ?? null; } /** diff --git a/includes/shell/FirejailCommand.php b/includes/shell/FirejailCommand.php index d8189304cb..7aed05f9be 100644 --- a/includes/shell/FirejailCommand.php +++ b/includes/shell/FirejailCommand.php @@ -65,7 +65,7 @@ class FirejailCommand extends Command { $splitCommand = explode( ' ', $command, 2 ); $this->logger->debug( "firejail: Command {$splitCommand[0]} {params} has no restrictions", - [ 'params' => isset( $splitCommand[1] ) ? $splitCommand[1] : '' ] + [ 'params' => $splitCommand[1] ?? '' ] ); return parent::buildFinalCommand( $command ); } diff --git a/includes/skins/BaseTemplate.php b/includes/skins/BaseTemplate.php index 156df67f2e..d1bea8d1b2 100644 --- a/includes/skins/BaseTemplate.php +++ b/includes/skins/BaseTemplate.php @@ -366,7 +366,7 @@ abstract class BaseTemplate extends QuickTemplate { if ( isset( $item['text'] ) ) { $text = $item['text']; } else { - $text = wfMessage( isset( $item['msg'] ) ? $item['msg'] : $key )->text(); + $text = wfMessage( $item['msg'] ?? $key )->text(); } $html = htmlspecialchars( $text ); @@ -378,9 +378,7 @@ abstract class BaseTemplate extends QuickTemplate { } while ( count( $wrapper ) > 0 ) { $element = array_pop( $wrapper ); - $html = Html::rawElement( $element['tag'], isset( $element['attributes'] ) - ? $element['attributes'] - : null, $html ); + $html = Html::rawElement( $element['tag'], $element['attributes'] ?? null, $html ); } } @@ -517,7 +515,7 @@ abstract class BaseTemplate extends QuickTemplate { if ( isset( $item['itemtitle'] ) ) { $attrs['title'] = $item['itemtitle']; } - return Html::rawElement( isset( $options['tag'] ) ? $options['tag'] : 'li', $attrs, $html ); + return Html::rawElement( $options['tag'] ?? 'li', $attrs, $html ); } function makeSearchInput( $attrs = [] ) { @@ -561,11 +559,9 @@ abstract class BaseTemplate extends QuickTemplate { unset( $buttonAttrs['height'] ); $imgAttrs = [ 'src' => $attrs['src'], - 'alt' => isset( $attrs['alt'] ) - ? $attrs['alt'] - : wfMessage( 'searchbutton' )->text(), - 'width' => isset( $attrs['width'] ) ? $attrs['width'] : null, - 'height' => isset( $attrs['height'] ) ? $attrs['height'] : null, + 'alt' => $attrs['alt'] ?? wfMessage( 'searchbutton' )->text(), + 'width' => $attrs['width'] ?? null, + 'height' => $attrs['height'] ?? null, ]; return Html::rawElement( 'button', $buttonAttrs, Html::element( 'img', $imgAttrs ) ); default: diff --git a/includes/skins/Skin.php b/includes/skins/Skin.php index 6739c08f8f..57ca2f481c 100644 --- a/includes/skins/Skin.php +++ b/includes/skins/Skin.php @@ -976,7 +976,7 @@ abstract class Skin extends ContextSource { if ( is_string( $icon ) ) { $html = $icon; } else { // Assuming array - $url = isset( $icon["url"] ) ? $icon["url"] : null; + $url = $icon["url"] ?? null; unset( $icon["url"] ); if ( isset( $icon["src"] ) && $withImage === 'withImage' ) { // do this the lazy way, just pass icon data as an attribute array @@ -1454,7 +1454,7 @@ abstract class Skin extends ContextSource { if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) { $uTalkTitle = $user->getTalkPage(); - $lastSeenRev = isset( $newtalks[0]['rev'] ) ? $newtalks[0]['rev'] : null; + $lastSeenRev = $newtalks[0]['rev'] ?? null; $nofAuthors = 0; if ( $lastSeenRev !== null ) { $plural = true; // Default if we have a last seen revision: if unknown, use plural diff --git a/includes/specialpage/ChangesListSpecialPage.php b/includes/specialpage/ChangesListSpecialPage.php index 1f1d46e9a6..0622584331 100644 --- a/includes/specialpage/ChangesListSpecialPage.php +++ b/includes/specialpage/ChangesListSpecialPage.php @@ -1196,9 +1196,7 @@ abstract class ChangesListSpecialPage extends SpecialPage { * @return ChangesListFilterGroup|null Group, or null if not registered */ public function getFilterGroup( $groupName ) { - return isset( $this->filterGroups[$groupName] ) ? - $this->filterGroups[$groupName] : - null; + return $this->filterGroups[$groupName] ?? null; } // Currently, this intentionally only includes filters that display @@ -1682,9 +1680,9 @@ abstract class ChangesListSpecialPage extends SpecialPage { unset( $legendItems['unpatrolled'] ); } foreach ( $legendItems as $key => $item ) { # generate items of the legend - $label = isset( $item['legend'] ) ? $item['legend'] : $item['title']; + $label = $item['legend'] ?? $item['title']; $letter = $item['letter']; - $cssClass = isset( $item['class'] ) ? $item['class'] : $key; + $cssClass = $item['class'] ?? $key; $legend .= Html::element( 'dt', [ 'class' => $cssClass ], $context->msg( $letter )->text() diff --git a/includes/specialpage/ImageQueryPage.php b/includes/specialpage/ImageQueryPage.php index 49aaffd004..8df64937e5 100644 --- a/includes/specialpage/ImageQueryPage.php +++ b/includes/specialpage/ImageQueryPage.php @@ -52,7 +52,7 @@ abstract class ImageQueryPage extends QueryPage { $i = 0; foreach ( $res as $row ) { $i++; - $namespace = isset( $row->namespace ) ? $row->namespace : NS_FILE; + $namespace = $row->namespace ?? NS_FILE; $title = Title::makeTitleSafe( $namespace, $row->title ); if ( $title instanceof Title && $title->getNamespace() == NS_FILE ) { $gallery->add( $title, $this->getCellHtml( $row ) ); diff --git a/includes/specialpage/LoginSignupSpecialPage.php b/includes/specialpage/LoginSignupSpecialPage.php index 1c54d13d97..45e9684c85 100644 --- a/includes/specialpage/LoginSignupSpecialPage.php +++ b/includes/specialpage/LoginSignupSpecialPage.php @@ -846,8 +846,7 @@ abstract class LoginSignupSpecialPage extends AuthManagerSpecialPage { // keep the ordering from getCoreFieldDescriptors() where there is no explicit weight foreach ( $coreFieldDescriptors as $fieldName => $coreField ) { - $requestField = isset( $formDescriptor[$fieldName] ) ? - $formDescriptor[$fieldName] : []; + $requestField = $formDescriptor[$fieldName] ?? []; // remove everything that is not in the fieldinfo, is not marked as a supplemental field // to something in the fieldinfo, is not B/C for the pre-AuthManager templates, diff --git a/includes/specialpage/QueryPage.php b/includes/specialpage/QueryPage.php index f642106af7..655b495e77 100644 --- a/includes/specialpage/QueryPage.php +++ b/includes/specialpage/QueryPage.php @@ -806,7 +806,7 @@ abstract class QueryPage extends SpecialPage { } $title = Title::makeTitle( intval( $row->namespace ), $row->title ); if ( $title ) { - $date = isset( $row->timestamp ) ? $row->timestamp : ''; + $date = $row->timestamp ?? ''; $comments = ''; if ( $title ) { $talkpage = $title->getTalkPage(); @@ -830,7 +830,7 @@ abstract class QueryPage extends SpecialPage { } function feedItemAuthor( $row ) { - return isset( $row->user_text ) ? $row->user_text : ''; + return $row->user_text ?? ''; } function feedTitle() { diff --git a/includes/specials/SpecialListgrouprights.php b/includes/specials/SpecialListgrouprights.php index cc62d6146a..6091a641d0 100644 --- a/includes/specials/SpecialListgrouprights.php +++ b/includes/specials/SpecialListgrouprights.php @@ -74,9 +74,7 @@ class SpecialListGroupRights extends SpecialPage { $linkRenderer = $this->getLinkRenderer(); foreach ( $allGroups as $group ) { - $permissions = isset( $groupPermissions[$group] ) - ? $groupPermissions[$group] - : []; + $permissions = $groupPermissions[$group] ?? []; $groupname = ( $group == '*' ) // Replace * with a more descriptive groupname ? 'all' : $group; @@ -114,13 +112,11 @@ class SpecialListGroupRights extends SpecialPage { $grouplink = ''; } - $revoke = isset( $revokePermissions[$group] ) ? $revokePermissions[$group] : []; - $addgroups = isset( $addGroups[$group] ) ? $addGroups[$group] : []; - $removegroups = isset( $removeGroups[$group] ) ? $removeGroups[$group] : []; - $addgroupsSelf = isset( $groupsAddToSelf[$group] ) ? $groupsAddToSelf[$group] : []; - $removegroupsSelf = isset( $groupsRemoveFromSelf[$group] ) - ? $groupsRemoveFromSelf[$group] - : []; + $revoke = $revokePermissions[$group] ?? []; + $addgroups = $addGroups[$group] ?? []; + $removegroups = $removeGroups[$group] ?? []; + $addgroupsSelf = $groupsAddToSelf[$group] ?? []; + $removegroupsSelf = $groupsRemoveFromSelf[$group] ?? []; $id = $group == '*' ? false : Sanitizer::escapeIdForAttribute( $group ); $out->addHTML( Html::rawElement( 'tr', [ 'id' => $id ], " diff --git a/includes/specials/SpecialMediaStatistics.php b/includes/specials/SpecialMediaStatistics.php index 943fa57062..26c9b06f4a 100644 --- a/includes/specials/SpecialMediaStatistics.php +++ b/includes/specials/SpecialMediaStatistics.php @@ -363,8 +363,8 @@ class MediaStatisticsPage extends QueryPage { $this->totalCount = $this->totalBytes = 0; foreach ( $res as $row ) { $mediaStats = $this->splitFakeTitle( $row->title ); - $this->totalCount += isset( $mediaStats[2] ) ? $mediaStats[2] : 0; - $this->totalBytes += isset( $mediaStats[3] ) ? $mediaStats[3] : 0; + $this->totalCount += $mediaStats[2] ?? 0; + $this->totalBytes += $mediaStats[3] ?? 0; } $res->seek( 0 ); } diff --git a/includes/specials/SpecialNewpages.php b/includes/specials/SpecialNewpages.php index cd3da4f0fa..a93b5222c0 100644 --- a/includes/specials/SpecialNewpages.php +++ b/includes/specials/SpecialNewpages.php @@ -483,7 +483,7 @@ class SpecialNewpages extends IncludableSpecialPage { } protected function feedItemAuthor( $row ) { - return isset( $row->rc_user_text ) ? $row->rc_user_text : ''; + return $row->rc_user_text ?? ''; } protected function feedItemDesc( $row ) { diff --git a/includes/specials/SpecialPasswordReset.php b/includes/specials/SpecialPasswordReset.php index 753923597b..7342bb0cc7 100644 --- a/includes/specials/SpecialPasswordReset.php +++ b/includes/specials/SpecialPasswordReset.php @@ -133,8 +133,8 @@ class SpecialPasswordReset extends FormSpecialPage { * @return Status */ public function onSubmit( array $data ) { - $username = isset( $data['Username'] ) ? $data['Username'] : null; - $email = isset( $data['Email'] ) ? $data['Email'] : null; + $username = $data['Username'] ?? null; + $email = $data['Email'] ?? null; $this->method = $username ? 'username' : 'email'; $this->result = Status::wrap( diff --git a/includes/specials/SpecialUserrights.php b/includes/specials/SpecialUserrights.php index a05452d014..22c6afeefd 100644 --- a/includes/specials/SpecialUserrights.php +++ b/includes/specials/SpecialUserrights.php @@ -373,7 +373,7 @@ class UserrightsPage extends SpecialPage { } if ( $add ) { foreach ( $add as $index => $group ) { - $expiry = isset( $groupExpiries[$group] ) ? $groupExpiries[$group] : null; + $expiry = $groupExpiries[$group] ?? null; if ( !$user->addGroup( $group, $expiry ) ) { unset( $add[$index] ); } diff --git a/includes/specials/SpecialVersion.php b/includes/specials/SpecialVersion.php index 13b6bdf9e7..0258433250 100644 --- a/includes/specials/SpecialVersion.php +++ b/includes/specials/SpecialVersion.php @@ -394,7 +394,7 @@ class SpecialVersion extends SpecialPage { public static function getExtensionTypeName( $type ) { $types = self::getExtensionTypes(); - return isset( $types[$type] ) ? $types[$type] : $types['other']; + return $types[$type] ?? $types['other']; } /** @@ -830,7 +830,7 @@ class SpecialVersion extends SpecialPage { $description = $out->parseInline( $description ); // ... now get the authors for this extension - $authors = isset( $extension['author'] ) ? $extension['author'] : []; + $authors = $extension['author'] ?? []; $authors = $this->listAuthors( $authors, $extension['name'], $extensionPath ); // Finally! Create the table diff --git a/includes/specials/SpecialWantedcategories.php b/includes/specials/SpecialWantedcategories.php index fc0c3123e3..d323c9e2b9 100644 --- a/includes/specials/SpecialWantedcategories.php +++ b/includes/specials/SpecialWantedcategories.php @@ -103,9 +103,7 @@ class WantedCategoriesPage extends WantedQueryPage { } else { $plink = $this->getLinkRenderer()->makeLink( $nt, $text ); - $currentValue = isset( $this->currentCategoryCounts[$result->title] ) - ? $this->currentCategoryCounts[$result->title] - : 0; + $currentValue = $this->currentCategoryCounts[$result->title] ?? 0; $cachedValue = intval( $result->value ); // T76910 // If the category has been created or emptied since the list was refreshed, strike it diff --git a/includes/specials/formfields/UploadSourceField.php b/includes/specials/formfields/UploadSourceField.php index 251a28667a..6dc129c38c 100644 --- a/includes/specials/formfields/UploadSourceField.php +++ b/includes/specials/formfields/UploadSourceField.php @@ -61,8 +61,6 @@ class UploadSourceField extends HTMLTextField { * @return int */ function getSize() { - return isset( $this->mParams['size'] ) - ? $this->mParams['size'] - : 60; + return $this->mParams['size'] ?? 60; } } diff --git a/includes/specials/forms/PreferencesFormLegacy.php b/includes/specials/forms/PreferencesFormLegacy.php index 48bded4e04..cae895f626 100644 --- a/includes/specials/forms/PreferencesFormLegacy.php +++ b/includes/specials/forms/PreferencesFormLegacy.php @@ -104,7 +104,7 @@ class PreferencesFormLegacy extends HTMLForm { foreach ( $this->mFlatFields as $fieldname => $field ) { if ( $field instanceof HTMLNestedFilterable ) { $info = $field->mParams; - $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $fieldname; + $prefix = $info['prefix'] ?? $fieldname; foreach ( $field->filterDataForSubmit( $data[$fieldname] ) as $key => $value ) { $data["$prefix$key"] = $value; } diff --git a/includes/specials/forms/PreferencesFormOOUI.php b/includes/specials/forms/PreferencesFormOOUI.php index 47a595f38b..423e2bb80a 100644 --- a/includes/specials/forms/PreferencesFormOOUI.php +++ b/includes/specials/forms/PreferencesFormOOUI.php @@ -105,7 +105,7 @@ class PreferencesFormOOUI extends OOUIHTMLForm { foreach ( $this->mFlatFields as $fieldname => $field ) { if ( $field instanceof HTMLNestedFilterable ) { $info = $field->mParams; - $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $fieldname; + $prefix = $info['prefix'] ?? $fieldname; foreach ( $field->filterDataForSubmit( $data[$fieldname] ) as $key => $value ) { $data["$prefix$key"] = $value; } diff --git a/includes/specials/forms/UploadForm.php b/includes/specials/forms/UploadForm.php index 8ab6f29f09..e37200f60f 100644 --- a/includes/specials/forms/UploadForm.php +++ b/includes/specials/forms/UploadForm.php @@ -55,19 +55,16 @@ class UploadForm extends HTMLForm { $this->mWatch = !empty( $options['watch'] ); $this->mForReUpload = !empty( $options['forreupload'] ); - $this->mSessionKey = isset( $options['sessionkey'] ) ? $options['sessionkey'] : ''; + $this->mSessionKey = $options['sessionkey'] ?? ''; $this->mHideIgnoreWarning = !empty( $options['hideignorewarning'] ); $this->mDestWarningAck = !empty( $options['destwarningack'] ); - $this->mDestFile = isset( $options['destfile'] ) ? $options['destfile'] : ''; + $this->mDestFile = $options['destfile'] ?? ''; - $this->mComment = isset( $options['description'] ) ? - $options['description'] : ''; + $this->mComment = $options['description'] ?? ''; - $this->mTextTop = isset( $options['texttop'] ) - ? $options['texttop'] : ''; + $this->mTextTop = $options['texttop'] ?? ''; - $this->mTextAfterSummary = isset( $options['textaftersummary'] ) - ? $options['textaftersummary'] : ''; + $this->mTextAfterSummary = $options['textaftersummary'] ?? ''; $sourceDescriptor = $this->getSourceSection(); $descriptor = $sourceDescriptor diff --git a/includes/specials/pagers/ContribsPager.php b/includes/specials/pagers/ContribsPager.php index e31498ac38..205364f81b 100644 --- a/includes/specials/pagers/ContribsPager.php +++ b/includes/specials/pagers/ContribsPager.php @@ -64,12 +64,12 @@ class ContribsPager extends RangeChronologicalPager { $this->messages[$msg] = $this->msg( $msg )->escaped(); } - $this->target = isset( $options['target'] ) ? $options['target'] : ''; - $this->contribs = isset( $options['contribs'] ) ? $options['contribs'] : 'users'; - $this->namespace = isset( $options['namespace'] ) ? $options['namespace'] : ''; - $this->tagFilter = isset( $options['tagfilter'] ) ? $options['tagfilter'] : false; - $this->nsInvert = isset( $options['nsInvert'] ) ? $options['nsInvert'] : false; - $this->associated = isset( $options['associated'] ) ? $options['associated'] : false; + $this->target = $options['target'] ?? ''; + $this->contribs = $options['contribs'] ?? 'users'; + $this->namespace = $options['namespace'] ?? ''; + $this->tagFilter = $options['tagfilter'] ?? false; + $this->nsInvert = $options['nsInvert'] ?? false; + $this->associated = $options['associated'] ?? false; $this->deletedOnly = !empty( $options['deletedOnly'] ); $this->topOnly = !empty( $options['topOnly'] ); @@ -640,10 +640,10 @@ class ContribsPager extends RangeChronologicalPager { * @return array Options array with processed start and end date filter options */ public static function processDateFilter( array $opts ) { - $start = isset( $opts['start'] ) ? $opts['start'] : ''; - $end = isset( $opts['end'] ) ? $opts['end'] : ''; - $year = isset( $opts['year'] ) ? $opts['year'] : ''; - $month = isset( $opts['month'] ) ? $opts['month'] : ''; + $start = $opts['start'] ?? ''; + $end = $opts['end'] ?? ''; + $year = $opts['year'] ?? ''; + $month = $opts['month'] ?? ''; if ( $start !== '' && $end !== '' && $start > $end ) { $temp = $start; diff --git a/includes/specials/pagers/DeletedContribsPager.php b/includes/specials/pagers/DeletedContribsPager.php index f3de64d6e5..b5ced1348e 100644 --- a/includes/specials/pagers/DeletedContribsPager.php +++ b/includes/specials/pagers/DeletedContribsPager.php @@ -256,7 +256,7 @@ class DeletedContribsPager extends IndexPager { 'comment' => CommentStore::getStore()->getComment( 'ar_comment', $row )->text, 'user' => $row->ar_user, 'user_text' => $row->ar_user_text, - 'actor' => isset( $row->ar_actor ) ? $row->ar_actor : null, + 'actor' => $row->ar_actor ?? null, 'timestamp' => $row->ar_timestamp, 'minor_edit' => $row->ar_minor_edit, 'deleted' => $row->ar_deleted, diff --git a/includes/specials/pagers/UsersPager.php b/includes/specials/pagers/UsersPager.php index d17332f6e7..23f9f838dc 100644 --- a/includes/specials/pagers/UsersPager.php +++ b/includes/specials/pagers/UsersPager.php @@ -411,7 +411,7 @@ class UsersPager extends AlphabeticPager { $user = User::newFromId( $uid ); return $user->getGroupMemberships(); } else { - return isset( $cache[$uid] ) ? $cache[$uid] : []; + return $cache[$uid] ?? []; } } diff --git a/includes/upload/UploadBase.php b/includes/upload/UploadBase.php index 064ca6728c..27c0ed7730 100644 --- a/includes/upload/UploadBase.php +++ b/includes/upload/UploadBase.php @@ -1864,8 +1864,7 @@ abstract class UploadBase { # look up scanner configuration $command = $wgAntivirusSetup[$wgAntivirus]['command']; $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap']; - $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ? - $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null; + $msgPattern = $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ?? null; if ( strpos( $command, "%f" ) === false ) { # simple pattern: append file to scan diff --git a/includes/user/BotPassword.php b/includes/user/BotPassword.php index 6b8153cde4..960a48644d 100644 --- a/includes/user/BotPassword.php +++ b/includes/user/BotPassword.php @@ -139,10 +139,8 @@ class BotPassword implements IDBAccessObject { 'bp_user' => 0, 'bp_app_id' => isset( $data['appId'] ) ? trim( $data['appId'] ) : '', 'bp_token' => '**unsaved**', - 'bp_restrictions' => isset( $data['restrictions'] ) - ? $data['restrictions'] - : MWRestrictions::newDefault(), - 'bp_grants' => isset( $data['grants'] ) ? $data['grants'] : [], + 'bp_restrictions' => $data['restrictions'] ?? MWRestrictions::newDefault(), + 'bp_grants' => $data['grants'] ?? [], ]; if ( diff --git a/includes/user/User.php b/includes/user/User.php index b5fa97ff2c..c5fa05a9a5 100644 --- a/includes/user/User.php +++ b/includes/user/User.php @@ -3335,7 +3335,7 @@ class User implements IDBAccessObject, UserIdentity { if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) || ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField::class ) ) { $opts = HTMLFormField::flattenOptions( $info['options'] ); - $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name; + $prefix = $info['prefix'] ?? $name; foreach ( $opts as $value ) { $multiselectOptions["$prefix$value"] = true; @@ -3350,7 +3350,7 @@ class User implements IDBAccessObject, UserIdentity { ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix::class ) ) { $columns = HTMLFormField::flattenOptions( $info['columns'] ); $rows = HTMLFormField::flattenOptions( $info['rows'] ); - $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name; + $prefix = $info['prefix'] ?? $name; foreach ( $columns as $column ) { foreach ( $rows as $row ) { diff --git a/includes/watcheditem/WatchedItemQueryService.php b/includes/watcheditem/WatchedItemQueryService.php index deb1f28b1a..17d9b91ac0 100644 --- a/includes/watcheditem/WatchedItemQueryService.php +++ b/includes/watcheditem/WatchedItemQueryService.php @@ -220,7 +220,7 @@ class WatchedItemQueryService { $joinConds ); - $limit = isset( $dbOptions['LIMIT'] ) ? $dbOptions['LIMIT'] : INF; + $limit = $dbOptions['LIMIT'] ?? INF; $items = []; $startFrom = null; foreach ( $res as $row ) { diff --git a/includes/widget/ComplexTitleInputWidget.php b/includes/widget/ComplexTitleInputWidget.php index ca6c8484d1..392e46dc89 100644 --- a/includes/widget/ComplexTitleInputWidget.php +++ b/includes/widget/ComplexTitleInputWidget.php @@ -40,9 +40,7 @@ class ComplexTitleInputWidget extends \OOUI\Widget { $config['title'], [ 'relative' => true, - 'namespace' => isset( $config['namespace']['value'] ) ? - $config['namespace']['value'] : - null, + 'namespace' => $config['namespace']['value'] ?? null, ] ) ); diff --git a/includes/widget/ExpiryInputWidget.php b/includes/widget/ExpiryInputWidget.php index 7395df1ce7..f9985eb9b2 100644 --- a/includes/widget/ExpiryInputWidget.php +++ b/includes/widget/ExpiryInputWidget.php @@ -42,7 +42,7 @@ class ExpiryInputWidget extends Widget { parent::__construct( $options ); $this->noDatePicker = $options['noDatePicker']; - $this->required = isset( $options['required'] ) ? $options['required'] : false; + $this->required = $options['required'] ?? false; // Properties $this->relativeInput = $relativeInput; diff --git a/includes/widget/NamespaceInputWidget.php b/includes/widget/NamespaceInputWidget.php index 0840886a79..7802a2a017 100644 --- a/includes/widget/NamespaceInputWidget.php +++ b/includes/widget/NamespaceInputWidget.php @@ -25,8 +25,8 @@ class NamespaceInputWidget extends \OOUI\DropdownInputWidget { parent::__construct( $config ); // Properties - $this->includeAllValue = isset( $config['includeAllValue'] ) ? $config['includeAllValue'] : null; - $this->exclude = isset( $config['exclude'] ) ? $config['exclude'] : []; + $this->includeAllValue = $config['includeAllValue'] ?? null; + $this->exclude = $config['exclude'] ?? []; // Initialization $this->addClasses( [ 'mw-widget-namespaceInputWidget' ] ); @@ -34,8 +34,8 @@ class NamespaceInputWidget extends \OOUI\DropdownInputWidget { protected function getNamespaceDropdownOptions( array $config ) { $namespaceOptionsParams = [ - 'all' => isset( $config['includeAllValue'] ) ? $config['includeAllValue'] : null, - 'exclude' => isset( $config['exclude'] ) ? $config['exclude'] : null + 'all' => $config['includeAllValue'] ?? null, + 'exclude' => $config['exclude'] ?? null ]; $namespaceOptions = \Html::namespaceSelectorOptions( $namespaceOptionsParams ); diff --git a/languages/Language.php b/languages/Language.php index 1320a57cb8..9d2bdb2e50 100644 --- a/languages/Language.php +++ b/languages/Language.php @@ -188,9 +188,7 @@ class Language { } // get the language object to process - $langObj = isset( self::$mLangObjCache[$code] ) - ? self::$mLangObjCache[$code] - : self::newFromCode( $code ); + $langObj = self::$mLangObjCache[$code] ?? self::newFromCode( $code ); // merge the language object in to get it up front in the cache self::$mLangObjCache = array_merge( [ $code => $langObj ], self::$mLangObjCache ); @@ -542,7 +540,7 @@ class Language { */ public function getNsText( $index ) { $ns = $this->getNamespaces(); - return isset( $ns[$index] ) ? $ns[$index] : false; + return $ns[$index] ?? false; } /** @@ -577,7 +575,7 @@ class Language { $ns = $wgExtraGenderNamespaces + (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' ); - return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index ); + return $ns[$index][$gender] ?? $this->getNsText( $index ); } /** @@ -613,7 +611,7 @@ class Language { function getLocalNsIndex( $text ) { $lctext = $this->lc( $text ); $ids = $this->getNamespaceIds(); - return isset( $ids[$lctext] ) ? $ids[$lctext] : false; + return $ids[$lctext] ?? false; } /** @@ -700,7 +698,7 @@ class Language { return $ns; } $ids = $this->getNamespaceIds(); - return isset( $ids[$lctext] ) ? $ids[$lctext] : false; + return $ids[$lctext] ?? false; } /** @@ -3960,7 +3958,7 @@ class Language { if ( $gender === 'female' ) { return $forms[1]; } - return isset( $forms[2] ) ? $forms[2] : $forms[0]; + return $forms[2] ?? $forms[0]; } /** diff --git a/maintenance/cleanupInvalidDbKeys.php b/maintenance/cleanupInvalidDbKeys.php index 54ed3aad1f..b9334348d4 100644 --- a/maintenance/cleanupInvalidDbKeys.php +++ b/maintenance/cleanupInvalidDbKeys.php @@ -123,15 +123,9 @@ TEXT protected function cleanupTable( $tableParams ) { $table = $tableParams[0]; $prefix = $tableParams[1]; - $idField = isset( $tableParams['idField'] ) ? - $tableParams['idField'] : - "{$prefix}_id"; - $nsField = isset( $tableParams['nsField'] ) ? - $tableParams['nsField'] : - "{$prefix}_namespace"; - $titleField = isset( $tableParams['titleField'] ) ? - $tableParams['titleField'] : - "{$prefix}_title"; + $idField = $tableParams['idField'] ?? "{$prefix}_id"; + $nsField = $tableParams['nsField'] ?? "{$prefix}_namespace"; + $titleField = $tableParams['titleField'] ?? "{$prefix}_title"; $this->outputStatus( "Looking for invalid $titleField entries in $table...\n" ); diff --git a/maintenance/copyFileBackend.php b/maintenance/copyFileBackend.php index 3c7ffba578..3374893755 100644 --- a/maintenance/copyFileBackend.php +++ b/maintenance/copyFileBackend.php @@ -337,9 +337,7 @@ class CopyFileBackend extends Maintenance { $dPathSha1 = sha1( $dPath ); if ( $this->statCache !== null ) { // All dst files are already in stat cache - $dstStat = isset( $this->statCache[$dPathSha1] ) - ? $this->statCache[$dPathSha1] - : false; + $dstStat = $this->statCache[$dPathSha1] ?? false; } else { $dstStat = $dst->getFileStat( [ 'src' => $dPath ] ); } diff --git a/maintenance/generateSitemap.php b/maintenance/generateSitemap.php index e2dc9b8263..b3e7aecf2f 100644 --- a/maintenance/generateSitemap.php +++ b/maintenance/generateSitemap.php @@ -276,9 +276,7 @@ class GenerateSitemap extends Maintenance { * @return string */ function priority( $namespace ) { - return isset( $this->priorities[$namespace] ) - ? $this->priorities[$namespace] - : $this->guessPriority( $namespace ); + return $this->priorities[$namespace] ?? $this->guessPriority( $namespace ); } /** diff --git a/maintenance/mcc.php b/maintenance/mcc.php index 784ba0ea35..e70060e2f6 100644 --- a/maintenance/mcc.php +++ b/maintenance/mcc.php @@ -30,7 +30,7 @@ require_once __DIR__ . '/commandLine.inc'; $debug = isset( $options['debug'] ); $help = isset( $options['help'] ); -$cache = isset( $options['cache'] ) ? $options['cache'] : null; +$cache = $options['cache'] ?? null; if ( $help ) { mccShowUsage(); diff --git a/maintenance/renameDbPrefix.php b/maintenance/renameDbPrefix.php index af8a2802d5..73bc4d9fea 100644 --- a/maintenance/renameDbPrefix.php +++ b/maintenance/renameDbPrefix.php @@ -50,7 +50,7 @@ class RenameDbPrefix extends Maintenance { } else { // Use nice safe, sane, prefixes preg_match( '/^[a-zA-Z]+_$/', $this->getOption( 'old' ), $m ); - $old = isset( $m[0] ) ? $m[0] : false; + $old = $m[0] ?? false; } // Allow for no new prefix if ( $this->getOption( 'new', 0 ) === '0' ) { @@ -58,7 +58,7 @@ class RenameDbPrefix extends Maintenance { } else { // Use nice safe, sane, prefixes preg_match( '/^[a-zA-Z]+_$/', $this->getOption( 'new' ), $m ); - $new = isset( $m[0] ) ? $m[0] : false; + $new = $m[0] ?? false; } if ( $old === false || $new === false ) { diff --git a/maintenance/storage/moveToExternal.php b/maintenance/storage/moveToExternal.php index 9bb554c64c..639ef5846f 100644 --- a/maintenance/storage/moveToExternal.php +++ b/maintenance/storage/moveToExternal.php @@ -43,7 +43,7 @@ if ( !defined( 'MEDIAWIKI' ) ) { } else { $maxID = $dbw->selectField( 'text', 'MAX(old_id)', '', $fname ); } - $minID = isset( $options['s'] ) ? $options['s'] : 1; + $minID = $options['s'] ?? 1; moveToExternal( $cluster, $maxID, $minID ); } diff --git a/maintenance/storage/testCompression.php b/maintenance/storage/testCompression.php index c3ed4fce0c..7cac7287c1 100644 --- a/maintenance/storage/testCompression.php +++ b/maintenance/storage/testCompression.php @@ -45,7 +45,7 @@ if ( isset( $options['limit'] ) ) { $limit = 1000; $untilHappy = true; } -$type = isset( $options['type'] ) ? $options['type'] : ConcatenatedGzipHistoryBlob::class; +$type = $options['type'] ?? ConcatenatedGzipHistoryBlob::class; $dbr = $this->getDB( DB_REPLICA ); $revQuery = Revision::getQueryInfo( [ 'page', 'text' ] ); diff --git a/maintenance/storage/trackBlobs.php b/maintenance/storage/trackBlobs.php index 36b6f5b459..2dd48caf98 100644 --- a/maintenance/storage/trackBlobs.php +++ b/maintenance/storage/trackBlobs.php @@ -122,7 +122,7 @@ class TrackBlobs { return [ 'cluster' => $m[1], 'id' => intval( $m[2] ), - 'hash' => isset( $m[3] ) ? $m[3] : null + 'hash' => $m[3] ?? null ]; } diff --git a/maintenance/updateSpecialPages.php b/maintenance/updateSpecialPages.php index 1491e62ac5..3c4d1f9f82 100644 --- a/maintenance/updateSpecialPages.php +++ b/maintenance/updateSpecialPages.php @@ -51,7 +51,7 @@ class UpdateSpecialPages extends Maintenance { foreach ( QueryPage::getPages() as $page ) { list( $class, $special ) = $page; - $limit = isset( $page[2] ) ? $page[2] : null; + $limit = $page[2] ?? null; # --list : just show the name of pages if ( $this->hasOption( 'list' ) ) { diff --git a/tests/parser/ParserTestRunner.php b/tests/parser/ParserTestRunner.php index ce1dae60ad..97175da631 100644 --- a/tests/parser/ParserTestRunner.php +++ b/tests/parser/ParserTestRunner.php @@ -143,8 +143,7 @@ class ParserTestRunner { $this->keepUploads = !empty( $options['keep-uploads'] ); - $this->fileBackendName = isset( $options['file-backend'] ) ? - $options['file-backend'] : false; + $this->fileBackendName = $options['file-backend'] ?? false; $this->runDisabled = !empty( $options['run-disabled'] ); $this->runParsoid = !empty( $options['run-parsoid'] ); @@ -465,7 +464,7 @@ class ParserTestRunner { if ( is_int( $name ) ) { $value(); } else { - $saved[$name] = isset( $GLOBALS[$name] ) ? $GLOBALS[$name] : null; + $saved[$name] = $GLOBALS[$name] ?? null; $GLOBALS[$name] = $value; } } @@ -537,7 +536,7 @@ class ParserTestRunner { * @return bool */ public function isSetupDone( $funcName ) { - return isset( $this->setupDone[$funcName] ) ? $this->setupDone[$funcName] : false; + return $this->setupDone[$funcName] ?? false; } /** @@ -837,7 +836,7 @@ class ParserTestRunner { } $local = isset( $opts['local'] ); - $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null; + $preprocessor = $opts['preprocessor'] ?? null; $parser = $this->getParser( $preprocessor ); $title = Title::newFromText( $titleText ); diff --git a/tests/phpunit/MediaWikiTestCase.php b/tests/phpunit/MediaWikiTestCase.php index 2e6c011584..da5cfb1527 100644 --- a/tests/phpunit/MediaWikiTestCase.php +++ b/tests/phpunit/MediaWikiTestCase.php @@ -950,13 +950,12 @@ abstract class MediaWikiTestCase extends PHPUnit\Framework\TestCase { $singletons = $wrappedProvider->singletons; if ( $provider instanceof MonologSpi ) { if ( !isset( $this->loggers[$channel] ) ) { - $this->loggers[$channel] = isset( $singletons['loggers'][$channel] ) - ? $singletons['loggers'][$channel] : null; + $this->loggers[$channel] = $singletons['loggers'][$channel] ?? null; } $singletons['loggers'][$channel] = $logger; } elseif ( $provider instanceof LegacySpi ) { if ( !isset( $this->loggers[$channel] ) ) { - $this->loggers[$channel] = isset( $singletons[$channel] ) ? $singletons[$channel] : null; + $this->loggers[$channel] = $singletons[$channel] ?? null; } $singletons[$channel] = $logger; } else { @@ -1410,8 +1409,7 @@ abstract class MediaWikiTestCase extends PHPUnit\Framework\TestCase { */ private function setUpSchema( IMaintainableDatabase $db ) { // Undo any active overrides. - $oldOverrides = isset( $db->_schemaOverrides ) ? $db->_schemaOverrides - : self::$schemaOverrideDefaults; + $oldOverrides = $db->_schemaOverrides ?? self::$schemaOverrideDefaults; if ( $oldOverrides['alter'] || $oldOverrides['create'] || $oldOverrides['drop'] ) { $this->undoSchemaOverrides( $db, $oldOverrides ); diff --git a/tests/phpunit/includes/GlobalFunctions/wfUrlencodeTest.php b/tests/phpunit/includes/GlobalFunctions/wfUrlencodeTest.php index 09c1040b2f..5d9f63daa7 100644 --- a/tests/phpunit/includes/GlobalFunctions/wfUrlencodeTest.php +++ b/tests/phpunit/includes/GlobalFunctions/wfUrlencodeTest.php @@ -33,9 +33,7 @@ class WfUrlencodeTest extends MediaWikiTestCase { $expected = $this->extractExpect( $server, $expectations ); // save up global - $old = isset( $_SERVER['SERVER_SOFTWARE'] ) - ? $_SERVER['SERVER_SOFTWARE'] - : null; + $old = $_SERVER['SERVER_SOFTWARE'] ?? null; $_SERVER['SERVER_SOFTWARE'] = $server; wfUrlencode( null ); diff --git a/tests/phpunit/includes/HtmlTest.php b/tests/phpunit/includes/HtmlTest.php index 6695fce3ba..974373b356 100644 --- a/tests/phpunit/includes/HtmlTest.php +++ b/tests/phpunit/includes/HtmlTest.php @@ -676,7 +676,7 @@ class HtmlTest extends MediaWikiTestCase { $ret[] = [ $case[0], $case[1], $case[2], - isset( $case[3] ) ? $case[3] : '' + $case[3] ?? '' ]; } diff --git a/tests/phpunit/includes/PrefixSearchTest.php b/tests/phpunit/includes/PrefixSearchTest.php index ed34a8ab9b..3bde5de41f 100644 --- a/tests/phpunit/includes/PrefixSearchTest.php +++ b/tests/phpunit/includes/PrefixSearchTest.php @@ -211,7 +211,7 @@ class PrefixSearchTest extends MediaWikiLangTestCase { public function testSearch( array $case ) { $this->searchProvision( null ); - $namespaces = isset( $case['namespaces'] ) ? $case['namespaces'] : []; + $namespaces = $case['namespaces'] ?? []; if ( wfGetDB( DB_REPLICA )->getType() === 'postgres' ) { // Postgres will sort lexicographically on utf8 code units (" " before "/") @@ -235,7 +235,7 @@ class PrefixSearchTest extends MediaWikiLangTestCase { public function testSearchWithOffset( array $case ) { $this->searchProvision( null ); - $namespaces = isset( $case['namespaces'] ) ? $case['namespaces'] : []; + $namespaces = $case['namespaces'] ?? []; $searcher = new StringPrefixSearch; $results = $searcher->search( $case['query'], 3, $namespaces, 1 ); diff --git a/tests/phpunit/includes/TestUserRegistry.php b/tests/phpunit/includes/TestUserRegistry.php index 0c178ca128..24aee24c9b 100644 --- a/tests/phpunit/includes/TestUserRegistry.php +++ b/tests/phpunit/includes/TestUserRegistry.php @@ -62,9 +62,7 @@ class TestUserRegistry { sort( $groups ); $key = implode( ',', $groups ); - $testUser = isset( self::$testUsers[$key] ) - ? self::$testUsers[$key] - : false; + $testUser = self::$testUsers[$key] ?? false; if ( !$testUser || !$testUser->getUser()->isLoggedIn() ) { $id = self::getNextId(); diff --git a/tests/phpunit/includes/api/ApiBaseTest.php b/tests/phpunit/includes/api/ApiBaseTest.php index cce99cebe0..b1f4e0c455 100644 --- a/tests/phpunit/includes/api/ApiBaseTest.php +++ b/tests/phpunit/includes/api/ApiBaseTest.php @@ -272,8 +272,7 @@ class ApiBaseTest extends ApiTestCase { $input !== null ? [ 'myParam' => $input ] : [] ) ); $wrapper->mMainModule = new ApiMain( $context ); - $parseLimits = isset( $options['parseLimits'] ) ? - $options['parseLimits'] : true; + $parseLimits = $options['parseLimits'] ?? true; if ( !empty( $options['apihighlimits'] ) ) { $context->setUser( self::$users['sysop']->getUser() ); @@ -1221,7 +1220,7 @@ class ApiBaseTest extends ApiTestCase { ]; foreach ( $integerTests as $test ) { - $desc = isset( $test[2] ) ? $test[2] : $test[0]; + $desc = $test[2] ?? $test[0]; $warnings = isset( $test[3] ) ? [ [ 'apiwarn-badutf8', 'myParam' ] ] : []; $returnArray["\"$desc\" as integer"] = [ diff --git a/tests/phpunit/includes/api/ApiComparePagesTest.php b/tests/phpunit/includes/api/ApiComparePagesTest.php index ea13a0d38e..04283357c6 100644 --- a/tests/phpunit/includes/api/ApiComparePagesTest.php +++ b/tests/phpunit/includes/api/ApiComparePagesTest.php @@ -113,7 +113,7 @@ class ApiComparePagesTest extends ApiTestCase { $value = self::$repl[$m[1]]; } else { $value = preg_replace_callback( '/{{REPL:(.+?)}}/', function ( $m ) { - return isset( self::$repl[$m[1]] ) ? self::$repl[$m[1]] : $m[0]; + return self::$repl[$m[1]] ?? $m[0]; }, $value ); } } elseif ( is_array( $value ) || is_object( $value ) ) { diff --git a/tests/phpunit/includes/api/ApiMainTest.php b/tests/phpunit/includes/api/ApiMainTest.php index d17334bb06..584c60c4ae 100644 --- a/tests/phpunit/includes/api/ApiMainTest.php +++ b/tests/phpunit/includes/api/ApiMainTest.php @@ -491,7 +491,7 @@ class ApiMainTest extends ApiTestCase { $module->expects( $this->any() ) ->method( 'getConditionalRequestData' ) ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) { - return isset( $conditions[$condition] ) ? $conditions[$condition] : null; + return $conditions[$condition] ?? null; } ) ); $ret = $priv->checkConditionalRequestHeaders( $module ); @@ -622,7 +622,7 @@ class ApiMainTest extends ApiTestCase { $module->expects( $this->any() ) ->method( 'getConditionalRequestData' ) ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) { - return isset( $conditions[$condition] ) ? $conditions[$condition] : null; + return $conditions[$condition] ?? null; } ) ); $priv->mModule = $module; @@ -630,7 +630,7 @@ class ApiMainTest extends ApiTestCase { foreach ( [ 'Last-Modified', 'ETag' ] as $header ) { $this->assertEquals( - isset( $headers[$header] ) ? $headers[$header] : null, + $headers[$header] ?? null, $response->getHeader( $header ), $header ); diff --git a/tests/phpunit/includes/api/format/ApiFormatBaseTest.php b/tests/phpunit/includes/api/format/ApiFormatBaseTest.php index 55f760f64d..d4aa80506e 100644 --- a/tests/phpunit/includes/api/format/ApiFormatBaseTest.php +++ b/tests/phpunit/includes/api/format/ApiFormatBaseTest.php @@ -59,7 +59,7 @@ class ApiFormatBaseTest extends ApiFormatTestBase { if ( $options['name'] !== 'mockfm' ) { $ct = 'text/x-mock'; $file = 'api-result.mock'; - $status = isset( $options['status'] ) ? $options['status'] : null; + $status = $options['status'] ?? null; } elseif ( isset( $params['wrappedhtml'] ) ) { $ct = 'text/mediawiki-api-prettyprint-wrapped'; $file = 'api-result-wrapped.json'; diff --git a/tests/phpunit/includes/api/format/ApiFormatTestBase.php b/tests/phpunit/includes/api/format/ApiFormatTestBase.php index 4169dab2be..ca20cb63f2 100644 --- a/tests/phpunit/includes/api/format/ApiFormatTestBase.php +++ b/tests/phpunit/includes/api/format/ApiFormatTestBase.php @@ -37,13 +37,13 @@ abstract class ApiFormatTestBase extends MediaWikiTestCase { if ( is_string( $options ) ) { $options = [ 'class' => $options ]; } - $printerName = isset( $options['name'] ) ? $options['name'] : $this->printerName; + $printerName = $options['name'] ?? $this->printerName; $context = new RequestContext; $context->setRequest( new FauxRequest( $params, true ) ); $main = new ApiMain( $context ); if ( isset( $options['class'] ) ) { - $factory = isset( $options['factory'] ) ? $options['factory'] : null; + $factory = $options['factory'] ?? null; $main->getModuleManager()->addModule( $printerName, 'format', $options['class'], $factory ); } $result = $main->getResult(); diff --git a/tests/phpunit/includes/api/generateRandomImages.php b/tests/phpunit/includes/api/generateRandomImages.php index d4a5acff07..9e7ef99b8a 100644 --- a/tests/phpunit/includes/api/generateRandomImages.php +++ b/tests/phpunit/includes/api/generateRandomImages.php @@ -30,7 +30,7 @@ class GenerateRandomImages extends Maintenance { ]; $options = getopt( null, $getOptSpec ); - $format = isset( $options['format'] ) ? $options['format'] : 'jpg'; + $format = $options['format'] ?? 'jpg'; unset( $options['format'] ); $number = isset( $options['number'] ) ? intval( $options['number'] ) : 10; diff --git a/tests/phpunit/includes/api/query/ApiQueryUserContribsTest.php b/tests/phpunit/includes/api/query/ApiQueryUserContribsTest.php index 1d0b47173e..82f3b92f05 100644 --- a/tests/phpunit/includes/api/query/ApiQueryUserContribsTest.php +++ b/tests/phpunit/includes/api/query/ApiQueryUserContribsTest.php @@ -107,7 +107,7 @@ class ApiQueryUserContribsTest extends ApiTestCase { $this->assertArrayHasKey( 'query', $apiResult[0], "Batching with limit $limit" ); $this->assertArrayHasKey( 'usercontribs', $apiResult[0]['query'], "Batching with limit $limit" ); - $continue = isset( $apiResult[0]['continue'] ) ? $apiResult[0]['continue'] : null; + $continue = $apiResult[0]['continue'] ?? null; foreach ( $apiResult[0]['query']['usercontribs'] as $page ) { $count++; $batchedIds[$page['user']][] = $page['revid']; diff --git a/tests/phpunit/includes/auth/AuthManagerTest.php b/tests/phpunit/includes/auth/AuthManagerTest.php index cc1624874f..d481eb4064 100644 --- a/tests/phpunit/includes/auth/AuthManagerTest.php +++ b/tests/phpunit/includes/auth/AuthManagerTest.php @@ -1063,7 +1063,7 @@ class AuthManagerTest extends \MediaWikiTestCase { } $state = $session->getSecret( 'AuthManager::authnState' ); - $maybeLink = isset( $state['maybeLink'] ) ? $state['maybeLink'] : []; + $maybeLink = $state['maybeLink'] ?? []; if ( $link && $response->status === AuthenticationResponse::RESTART ) { $this->assertEquals( $response->createRequest->maybeLink, diff --git a/tests/phpunit/includes/cache/GenderCacheTest.php b/tests/phpunit/includes/cache/GenderCacheTest.php index e5bb2379ef..5c1a925eac 100644 --- a/tests/phpunit/includes/cache/GenderCacheTest.php +++ b/tests/phpunit/includes/cache/GenderCacheTest.php @@ -41,7 +41,7 @@ class GenderCacheTest extends MediaWikiLangTestCase { */ public function testUserName( $userKey, $expectedGender ) { $genderCache = MediaWikiServices::getInstance()->getGenderCache(); - $username = isset( self::$nameMap[$userKey] ) ? self::$nameMap[$userKey] : $userKey; + $username = self::$nameMap[$userKey] ?? $userKey; $gender = $genderCache->getGenderOf( $username ); $this->assertEquals( $gender, $expectedGender, "GenderCache normal" ); } @@ -53,7 +53,7 @@ class GenderCacheTest extends MediaWikiLangTestCase { * @covers GenderCache::getGenderOf */ public function testUserObjects( $userKey, $expectedGender ) { - $username = isset( self::$nameMap[$userKey] ) ? self::$nameMap[$userKey] : $userKey; + $username = self::$nameMap[$userKey] ?? $userKey; $genderCache = MediaWikiServices::getInstance()->getGenderCache(); $gender = $genderCache->getGenderOf( $username ); $this->assertEquals( $gender, $expectedGender, "GenderCache normal" ); @@ -79,7 +79,7 @@ class GenderCacheTest extends MediaWikiLangTestCase { * @covers GenderCache::getGenderOf */ public function testStripSubpages( $userKey, $expectedGender ) { - $username = isset( self::$nameMap[$userKey] ) ? self::$nameMap[$userKey] : $userKey; + $username = self::$nameMap[$userKey] ?? $userKey; $genderCache = MediaWikiServices::getInstance()->getGenderCache(); $gender = $genderCache->getGenderOf( "$username/subpage" ); $this->assertEquals( $gender, $expectedGender, "GenderCache must strip of subpages" ); diff --git a/tests/phpunit/includes/db/DatabaseTestHelper.php b/tests/phpunit/includes/db/DatabaseTestHelper.php index e9fc34fa16..0795609a24 100644 --- a/tests/phpunit/includes/db/DatabaseTestHelper.php +++ b/tests/phpunit/includes/db/DatabaseTestHelper.php @@ -47,7 +47,7 @@ class DatabaseTestHelper extends Database { $this->profiler = new ProfilerStub( [] ); $this->trxProfiler = new TransactionProfiler(); - $this->cliMode = isset( $opts['cliMode'] ) ? $opts['cliMode'] : true; + $this->cliMode = $opts['cliMode'] ?? true; $this->connLogger = new \Psr\Log\NullLogger(); $this->queryLogger = new \Psr\Log\NullLogger(); $this->errorLogger = function ( Exception $e ) { @@ -198,9 +198,7 @@ class DatabaseTestHelper extends Database { } protected function wasKnownStatementRollbackError() { - return isset( $this->lastError['wasKnownStatementRollbackError'] ) - ? $this->lastError['wasKnownStatementRollbackError'] - : false; + return $this->lastError['wasKnownStatementRollbackError'] ?? false; } function fieldInfo( $table, $field ) { diff --git a/tests/phpunit/includes/libs/rdbms/database/DatabaseSQLTest.php b/tests/phpunit/includes/libs/rdbms/database/DatabaseSQLTest.php index 84c0c1c4db..d9919e15a4 100644 --- a/tests/phpunit/includes/libs/rdbms/database/DatabaseSQLTest.php +++ b/tests/phpunit/includes/libs/rdbms/database/DatabaseSQLTest.php @@ -53,10 +53,10 @@ class DatabaseSQLTest extends PHPUnit\Framework\TestCase { $this->database->select( $sql['tables'], $sql['fields'], - isset( $sql['conds'] ) ? $sql['conds'] : [], + $sql['conds'] ?? [], __METHOD__, - isset( $sql['options'] ) ? $sql['options'] : [], - isset( $sql['join_conds'] ) ? $sql['join_conds'] : [] + $sql['options'] ?? [], + $sql['join_conds'] ?? [] ); $this->assertLastSql( $sqlText ); } @@ -266,10 +266,10 @@ class DatabaseSQLTest extends PHPUnit\Framework\TestCase { $this->database->selectRowCount( $sql['tables'], $sql['field'], - isset( $sql['conds'] ) ? $sql['conds'] : [], + $sql['conds'] ?? [], __METHOD__, - isset( $sql['options'] ) ? $sql['options'] : [], - isset( $sql['join_conds'] ) ? $sql['join_conds'] : [] + $sql['options'] ?? [], + $sql['join_conds'] ?? [] ); $this->assertLastSql( $sqlText ); } @@ -363,7 +363,7 @@ class DatabaseSQLTest extends PHPUnit\Framework\TestCase { $sql['values'], $sql['conds'], __METHOD__, - isset( $sql['options'] ) ? $sql['options'] : [] + $sql['options'] ?? [] ); $this->assertLastSql( $sqlText ); } @@ -531,7 +531,7 @@ class DatabaseSQLTest extends PHPUnit\Framework\TestCase { $sql['table'], $sql['rows'], __METHOD__, - isset( $sql['options'] ) ? $sql['options'] : [] + $sql['options'] ?? [] ); $this->assertLastSql( $sqlText ); } @@ -587,9 +587,9 @@ class DatabaseSQLTest extends PHPUnit\Framework\TestCase { $sql['varMap'], $sql['conds'], __METHOD__, - isset( $sql['insertOptions'] ) ? $sql['insertOptions'] : [], - isset( $sql['selectOptions'] ) ? $sql['selectOptions'] : [], - isset( $sql['selectJoinConds'] ) ? $sql['selectJoinConds'] : [] + $sql['insertOptions'] ?? [], + $sql['selectOptions'] ?? [], + $sql['selectJoinConds'] ?? [] ); $this->assertLastSql( $sqlTextNative ); @@ -603,9 +603,9 @@ class DatabaseSQLTest extends PHPUnit\Framework\TestCase { $sql['varMap'], $sql['conds'], __METHOD__, - isset( $sql['insertOptions'] ) ? $sql['insertOptions'] : [], - isset( $sql['selectOptions'] ) ? $sql['selectOptions'] : [], - isset( $sql['selectJoinConds'] ) ? $sql['selectJoinConds'] : [] + $sql['insertOptions'] ?? [], + $sql['selectOptions'] ?? [], + $sql['selectJoinConds'] ?? [] ); $this->assertLastSqlDb( implode( '; ', [ $sqlSelect, 'BEGIN', $sqlInsert, 'COMMIT' ] ), $dbWeb ); } @@ -1012,10 +1012,10 @@ class DatabaseSQLTest extends PHPUnit\Framework\TestCase { $params['table'], $params['vars'], $params['permute_conds'], - isset( $params['extra_conds'] ) ? $params['extra_conds'] : '', + $params['extra_conds'] ?? '', 'FNAME', - isset( $params['options'] ) ? $params['options'] : [], - isset( $params['join_conds'] ) ? $params['join_conds'] : [] + $params['options'] ?? [], + $params['join_conds'] ?? [] ) ); $this->assertEquals( $expect, $sql ); } diff --git a/tests/phpunit/includes/logging/LogFormatterTestCase.php b/tests/phpunit/includes/logging/LogFormatterTestCase.php index 786d761900..883af71240 100644 --- a/tests/phpunit/includes/logging/LogFormatterTestCase.php +++ b/tests/phpunit/includes/logging/LogFormatterTestCase.php @@ -33,19 +33,19 @@ abstract class LogFormatterTestCase extends MediaWikiLangTestCase { // no log_id because no insert in database 'log_type' => $data['type'], 'log_action' => $data['action'], - 'log_timestamp' => isset( $data['timestamp'] ) ? $data['timestamp'] : wfTimestampNow(), - 'log_user' => isset( $data['user'] ) ? $data['user'] : 0, - 'log_user_text' => isset( $data['user_text'] ) ? $data['user_text'] : 'User', - 'log_actor' => isset( $data['actor'] ) ? $data['actor'] : 0, - 'log_namespace' => isset( $data['namespace'] ) ? $data['namespace'] : NS_MAIN, - 'log_title' => isset( $data['title'] ) ? $data['title'] : 'Main_Page', - 'log_page' => isset( $data['page'] ) ? $data['page'] : 0, - 'log_comment_text' => isset( $data['comment'] ) ? $data['comment'] : '', + 'log_timestamp' => $data['timestamp'] ?? wfTimestampNow(), + 'log_user' => $data['user'] ?? 0, + 'log_user_text' => $data['user_text'] ?? 'User', + 'log_actor' => $data['actor'] ?? 0, + 'log_namespace' => $data['namespace'] ?? NS_MAIN, + 'log_title' => $data['title'] ?? 'Main_Page', + 'log_page' => $data['page'] ?? 0, + 'log_comment_text' => $data['comment'] ?? '', 'log_comment_data' => null, 'log_params' => $legacy ? LogPage::makeParamBlob( $data['params'] ) : LogEntryBase::makeParamBlob( $data['params'] ), - 'log_deleted' => isset( $data['deleted'] ) ? $data['deleted'] : 0, + 'log_deleted' => $data['deleted'] ?? 0, ]; } diff --git a/tests/phpunit/includes/resourceloader/ResourceLoaderStartUpModuleTest.php b/tests/phpunit/includes/resourceloader/ResourceLoaderStartUpModuleTest.php index ca4fb34139..698370463a 100644 --- a/tests/phpunit/includes/resourceloader/ResourceLoaderStartUpModuleTest.php +++ b/tests/phpunit/includes/resourceloader/ResourceLoaderStartUpModuleTest.php @@ -463,7 +463,7 @@ mw.loader.register( [ $this->setMwGlobals( 'wgResourceLoaderSources', $case['sources'] ); } - $extraQuery = isset( $case['extraQuery'] ) ? $case['extraQuery'] : []; + $extraQuery = $case['extraQuery'] ?? []; $context = $this->getResourceLoaderContext( $extraQuery ); $rl = $context->getResourceLoader(); $rl->register( $case['modules'] ); diff --git a/tests/phpunit/includes/specialpage/AbstractChangesListSpecialPageTestCase.php b/tests/phpunit/includes/specialpage/AbstractChangesListSpecialPageTestCase.php index 8b8ba0c0e1..d84fcd70d6 100644 --- a/tests/phpunit/includes/specialpage/AbstractChangesListSpecialPageTestCase.php +++ b/tests/phpunit/includes/specialpage/AbstractChangesListSpecialPageTestCase.php @@ -101,7 +101,7 @@ abstract class AbstractChangesListSpecialPageTestCase extends MediaWikiTestCase $output->method( 'redirect' )->willReturnCallback( function ( $url ) use ( &$redirectQuery, &$redirected ) { $urlParts = wfParseUrl( $url ); - $query = isset( $urlParts[ 'query' ] ) ? $urlParts[ 'query' ] : ''; + $query = $urlParts[ 'query' ] ?? ''; parse_str( $query, $redirectQuery ); $redirected = true; } diff --git a/tests/qunit/data/styleTest.css.php b/tests/qunit/data/styleTest.css.php index e37f67d49f..db96fd5325 100644 --- a/tests/qunit/data/styleTest.css.php +++ b/tests/qunit/data/styleTest.css.php @@ -44,9 +44,9 @@ function cssfilter( $val ) { $params = array_map( 'cssfilter', $_GET ); // Defaults -$selector = isset( $params['selector'] ) ? $params['selector'] : '.mw-test-example'; -$property = isset( $params['prop'] ) ? $params['prop'] : 'float'; -$value = isset( $params['val'] ) ? $params['val'] : 'right'; +$selector = $params['selector'] ?? '.mw-test-example'; +$property = $params['prop'] ?? 'float'; +$value = $params['val'] ?? 'right'; $wait = isset( $params['wait'] ) ? (int)$params['wait'] : 0; // seconds sleep( $wait ); diff --git a/thumb.php b/thumb.php index a3c9d84452..b59116eaed 100644 --- a/thumb.php +++ b/thumb.php @@ -94,7 +94,7 @@ function wfStreamThumb( array $params ) { $headers = []; // HTTP headers to send - $fileName = isset( $params['f'] ) ? $params['f'] : ''; + $fileName = $params['f'] ?? ''; // Backwards compatibility parameters if ( isset( $params['w'] ) ) { @@ -244,7 +244,7 @@ function wfStreamThumb( array $params ) { } } - $rel404 = isset( $params['rel404'] ) ? $params['rel404'] : null; + $rel404 = $params['rel404'] ?? null; unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER unset( $params['f'] ); // We're done with 'f' parameter. unset( $params['rel404'] ); // moved to $rel404 @@ -648,7 +648,7 @@ function wfThumbError( $status, $msgHtml, $msgText = null, $context = [] ) { if ( $wgShowHostnames ) { header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() ); $url = htmlspecialchars( - isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '', + $_SERVER['REQUEST_URI'] ?? '', ENT_NOQUOTES ); $hostname = htmlspecialchars( wfHostname(), ENT_NOQUOTES ); -- 2.20.1