jenkins-bot has submitted this change and it was merged. ( https://gerrit.wikimedia.org/r/364039 )
Change subject: build: Updating mediawiki/mediawiki-codesniffer to 0.10.1 ...................................................................... build: Updating mediawiki/mediawiki-codesniffer to 0.10.1 Change-Id: I5f9d1c386ffe6ecf6c483c67471a9f14080c7c77 --- M CentralNotice.hooks.php M api/ApiCentralNoticeChoiceData.php M composer.json M includes/AllocationCalculator.php M includes/Banner.php M includes/BannerMessage.php M includes/BannerMessageGroup.php M includes/BannerRenderer.php M includes/CNBannerPager.php M includes/CNCampaignPager.php M includes/CNChoiceDataResourceLoaderModule.php M includes/CNDatabase.php M includes/CNDeviceTarget.php M includes/Campaign.php M includes/CampaignLog.php M includes/CdnCacheUpdateBannerLoader.php M includes/ChoiceDataProvider.php M includes/HtmlFormElements/HTMLCentralNoticeBanner.php M patches/CNDatabasePatcher.php M phpcs.xml M special/SpecialBannerAllocation.php M special/SpecialBannerLoader.php M special/SpecialCNReporter.php M special/SpecialCentralNotice.php M special/SpecialCentralNoticeBanners.php M special/SpecialCentralNoticeLogs.php M special/SpecialGlobalAllocation.php M special/SpecialHideBanners.php M tests/AllocationCalculatorTest.php M tests/ApiCentralNoticeChoiceDataTest.php M tests/BannerTest.php M tests/CNChoiceDataResourceLoaderModuleTest.php M tests/CentralNoticeTestFixtures.php M tests/ChoiceDataProviderTest.php 34 files changed, 297 insertions(+), 378 deletions(-) Approvals: jenkins-bot: Verified Jforrester: Looks good to me, approved diff --git a/CentralNotice.hooks.php b/CentralNotice.hooks.php index bcaa49d..b980767 100644 --- a/CentralNotice.hooks.php +++ b/CentralNotice.hooks.php @@ -170,7 +170,8 @@ // If we're editing or we're on a special page, bow out now if ( $out->getTitle()->inNamespace( NS_SPECIAL ) || - ( $wgRequest->getText( 'action' ) === 'edit' ) ) { + ( $wgRequest->getText( 'action' ) === 'edit' ) + ) { return true; } @@ -221,7 +222,6 @@ // This is useful for banners that need to be targeted to specific types of users. // Only do this for logged-in users, keeping anonymous user output equal (for Squid-cache). if ( $wgUser->isLoggedIn() ) { - $cacheKey = wfMemcKey( 'CentralNotice', 'UserData', $wgUser->getId() ); $userData = $wgMemc->get( $cacheKey ); @@ -381,14 +381,12 @@ // find test files for every RL module $prefix = 'ext.centralNotice'; foreach ( $wgResourceModules as $key => $module ) { - if ( substr( $key, 0, strlen( $prefix ) ) === - $prefix && isset( $module['scripts'] ) ) { - + $prefix && isset( $module['scripts'] ) + ) { $testFiles = []; foreach ( ( (array)$module['scripts'] ) as $script ) { - $testFile = 'tests/qunit/' . $script; $testFile = preg_replace( '/.js$/', '.tests.js', $testFile ); @@ -401,7 +399,6 @@ // if test files exist for given module, create a corresponding test // module if ( count( $testFiles ) > 0 ) { - $testModules['qunit']["$key.tests"] = $testModuleBoilerplate + [ 'dependencies' => diff --git a/api/ApiCentralNoticeChoiceData.php b/api/ApiCentralNoticeChoiceData.php index 0c01747..b281b5f 100644 --- a/api/ApiCentralNoticeChoiceData.php +++ b/api/ApiCentralNoticeChoiceData.php @@ -23,7 +23,6 @@ const STATUS_FILTER = '/loggedin|anonymous/'; public function execute() { - // Extract, sanitize and munge the parameters $params = $this->extractRequestParams(); @@ -46,7 +45,7 @@ null, 'choices', $choices - ); + ); } public function getAllowedParams() { diff --git a/composer.json b/composer.json index b8f68fb..fd295f4 100644 --- a/composer.json +++ b/composer.json @@ -2,12 +2,12 @@ "require-dev": { "jakub-onderka/php-parallel-lint": "0.9.2", "jakub-onderka/php-console-highlighter": "0.3.2", - "mediawiki/mediawiki-codesniffer": "0.7.2" + "mediawiki/mediawiki-codesniffer": "0.10.1" }, "scripts": { "fix": "phpcbf", "test": [ - "parallel-lint . --exclude vendor", + "parallel-lint . --exclude vendor --exclude node_modules", "phpcs -p -s" ] } diff --git a/includes/AllocationCalculator.php b/includes/AllocationCalculator.php index b6d40e3..935d15c 100644 --- a/includes/AllocationCalculator.php +++ b/includes/AllocationCalculator.php @@ -48,30 +48,29 @@ * @param string $device target device code */ public static function filterChoiceData( &$choiceData, $country, $status, $device ) { - $filteredChoiceData = []; foreach ( $choiceData as $campaign ) { - $keepCampaign = false; // Filter for country if geotargeted if ( $campaign['geotargeted'] && - !in_array( $country, $campaign['countries'] ) ) { - + !in_array( $country, $campaign['countries'] ) + ) { continue; } // Now filter by banner logged-in status and device foreach ( $campaign['banners'] as $banner ) { - // Logged-in status - if ( $status === AllocationCalculator::ANONYMOUS && - !$banner['display_anon'] ) { + if ( $status === self::ANONYMOUS && + !$banner['display_anon'] + ) { continue; } - if ( $status === AllocationCalculator::LOGGED_IN && - !$banner['display_account'] ) { + if ( $status === self::LOGGED_IN && + !$banner['display_account'] + ) { continue; } @@ -104,7 +103,6 @@ * filteredChoiceData(). */ public static function calculateCampaignAllocations( &$filteredChoiceData ) { - // Make an index of campaigns by priority level. // Note that the actual values of priority levels are integers, // and higher integers represent higher priority. These values are @@ -128,7 +126,6 @@ $remainingAllocation = 1; foreach ( $campaignsByPriority as $priority => &$campaignsAtThisPriority ) { - // If we fully allocated at a previous level, set allocations // at this level to zero. (We check with 0.01 instead of 0 in // case of issues due to finite precision.) @@ -167,7 +164,6 @@ $campaignsAtThisPriorityCount = count( $campaignsAtThisPriority ); foreach ( $campaignsAtThisPriority as $i => &$campaign ) { - // Calculate the proportional, unthrottled allocation now // available to a campaign at this level. $currentFullAllocation = @@ -205,23 +201,23 @@ * @return array of banner information as arrays */ public static function makePossibleBanners( $campaign, $bucket, $status, $device ) { - $banners = []; foreach ( $campaign['banners'] as $banner ) { - // Filter for bucket if ( $bucket % $campaign['bucket_count'] != $banner['bucket'] ) { continue; } // Filter for logged-in status - if ( $status === AllocationCalculator::ANONYMOUS && - !$banner['display_anon'] ) { + if ( $status === self::ANONYMOUS && + !$banner['display_anon'] + ) { continue; } - if ( $status === AllocationCalculator::LOGGED_IN && - !$banner['display_account'] ) { + if ( $status === self::LOGGED_IN && + !$banner['display_account'] + ) { continue; } @@ -245,7 +241,6 @@ * Each banner's 'allocation' property will be set. */ public static function calculateBannerAllocations( &$banners ) { - $totalWeights = 0; // Find the sum of all banner weights @@ -280,31 +275,30 @@ * @return array */ public static function filterAndAllocate( - $country, $status, $device, $bucket, $campaigns ) { - + $country, $status, $device, $bucket, $campaigns + ) { // Filter and determine campaign allocation - AllocationCalculator::filterChoiceData( + self::filterChoiceData( $campaigns, $country, $status, $device ); - AllocationCalculator::calculateCampaignAllocations( $campaigns ); + self::calculateCampaignAllocations( $campaigns ); // Go through all campaings to make a flat list of banners from all of // them, and calculate overall relative allocations. $possibleBannersAllCampaigns = []; foreach ( $campaigns as $campaign ) { - - $possibleBanners = AllocationCalculator::makePossibleBanners( + $possibleBanners = self::makePossibleBanners( $campaign, $bucket, $status, $device ); - AllocationCalculator::calculateBannerAllocations( $possibleBanners ); + self::calculateBannerAllocations( $possibleBanners ); foreach ( $possibleBanners as $banner ) { $banner['campaign'] = $campaign['name']; @@ -325,9 +319,9 @@ public static function getLoggedInStatusFromString( $s ) { switch ( $s ) { case 'anonymous': - return AllocationCalculator::ANONYMOUS; + return self::ANONYMOUS; case 'logged_in': - return AllocationCalculator::LOGGED_IN; + return self::LOGGED_IN; default: throw new InvalidArgumentException( 'Invalid logged-in status.' ); } diff --git a/includes/Banner.php b/includes/Banner.php index c107213..a2426e2 100644 --- a/includes/Banner.php +++ b/includes/Banner.php @@ -59,7 +59,7 @@ // <editor-fold desc="Properties"> // !!! NOTE !!! It is not recommended to use directly. It is almost always more - // correct to use the accessor/setter function. + // correct to use the accessor/setter function. /** @var int Unique database identifier key. */ protected $id = null; @@ -122,7 +122,7 @@ * @throws BannerDataException */ public static function fromName( $name ) { - if ( !Banner::isValidBannerName( $name ) ) { + if ( !self::isValidBannerName( $name ) ) { throw new BannerDataException( "Invalid banner name supplied." ); } @@ -140,7 +140,7 @@ * @throws BannerDataException */ public static function newFromName( $name ) { - if ( !Banner::isValidBannerName( $name ) ) { + if ( !self::isValidBannerName( $name ) ) { throw new BannerDataException( "Invalid banner name supplied." ); } @@ -320,12 +320,12 @@ $rowRes = $db->select( [ 'templates' => 'cn_templates' ], [ - 'tmp_id', - 'tmp_name', - 'tmp_display_anon', - 'tmp_display_account', - 'tmp_archived', - 'tmp_category' + 'tmp_id', + 'tmp_name', + 'tmp_display_anon', + 'tmp_display_account', + 'tmp_archived', + 'tmp_category' ], $selector, __METHOD__ @@ -380,13 +380,13 @@ if ( $this->dirtyFlags['basic'] ) { $db->update( 'cn_templates', [ - 'tmp_display_anon' => (int)$this->allocateAnon, - 'tmp_display_account' => (int)$this->allocateLoggedIn, - 'tmp_archived' => (int)$this->archived, - 'tmp_category' => $this->category, + 'tmp_display_anon' => (int)$this->allocateAnon, + 'tmp_display_account' => (int)$this->allocateLoggedIn, + 'tmp_archived' => (int)$this->archived, + 'tmp_category' => $this->category, ], [ - 'tmp_id' => $this->id + 'tmp_id' => $this->id ], __METHOD__ ); @@ -457,13 +457,13 @@ $rowObj = $db->select( [ - 'tdev' => 'cn_template_devices', - 'devices' => 'cn_known_devices' + 'tdev' => 'cn_template_devices', + 'devices' => 'cn_known_devices' ], [ 'devices.dev_id', 'dev_name' ], [ - 'tdev.tmp_id' => $this->getId(), - 'tdev.dev_id = devices.dev_id' + 'tdev.tmp_id' => $this->getId(), + 'tdev.dev_id = devices.dev_id' ], __METHOD__ ); @@ -560,7 +560,7 @@ $result = $dbr->select( 'cn_template_mixins', 'mixin_name', [ - "tmp_id" => $this->getId(), + "tmp_id" => $this->getId(), ], __METHOD__ ); @@ -607,9 +607,9 @@ } $db->insert( 'cn_template_mixins', [ - 'tmp_id' => $this->getId(), - 'page_id' => 0, // TODO: What were we going to use this for again? - 'mixin_name' => $name, + 'tmp_id' => $this->getId(), + 'page_id' => 0, // TODO: What were we going to use this for again? + 'mixin_name' => $name, ], __METHOD__ ); @@ -710,7 +710,6 @@ * @return string[] */ public function getCampaignNames() { - $dbr = CNDatabase::getDb(); $result = $dbr->select( @@ -828,7 +827,7 @@ $fields = $this->extractMessageFields(); if ( count( $fields ) > 0 ) { // Tag the banner for translation - Banner::addTag( 'banner:translate', $revisionId, $pageId, $this->getId() ); + self::addTag( 'banner:translate', $revisionId, $pageId, $this->getId() ); $this->runTranslateJob = true; } } @@ -928,8 +927,8 @@ $result = $db->select( 'page', 'page_title', [ - 'page_namespace' => $inTranslation ? NS_CN_BANNER : NS_MEDIAWIKI, - 'page_title' . $db->buildLike( $prefix, $db->anyString() ), + 'page_namespace' => $inTranslation ? NS_CN_BANNER : NS_MEDIAWIKI, + 'page_title' . $db->buildLike( $prefix, $db->anyString() ), ], __METHOD__ ); @@ -1070,7 +1069,7 @@ throw new BannerDataException( "Banner name must be in format /^[A-Za-z0-9_]+$/" ); } - $destBanner = Banner::newFromName( $destination ); + $destBanner = self::newFromName( $destination ); if ( $destBanner->exists() ) { throw new BannerExistenceException( "Banner by that name already exists!" ); } @@ -1106,13 +1105,13 @@ if ( $user === null ) { $user = $wgUser; } - Banner::removeTemplate( $this->getName(), $user ); + self::removeTemplate( $this->getName(), $user ); } static function removeTemplate( $name, $user, $summary = null ) { global $wgNoticeUseTranslateExtension; - $bannerObj = Banner::fromName( $name ); + $bannerObj = self::fromName( $name ); $id = $bannerObj->getId(); $dbr = CNDatabase::getDb(); $res = $dbr->select( 'cn_assignments', 'asn_id', [ 'tmp_id' => $id ], __METHOD__ ); @@ -1142,7 +1141,7 @@ if ( $wgNoticeUseTranslateExtension ) { // Remove any revision tags related to the banner - Banner::removeTag( 'banner:translate', $pageId ); + self::removeTag( 'banner:translate', $pageId ); // And the preferred language metadata if it exists TranslateMetadata::set( @@ -1172,7 +1171,7 @@ } // There should only ever be one tag applied to a banner object - Banner::removeTag( $tag, $pageId ); + self::removeTag( $tag, $pageId ); $conds = [ 'rt_page' => $pageId, @@ -1247,9 +1246,9 @@ __METHOD__, [], [ - 'template_devices' => [ - 'LEFT JOIN', 'template_devices.tmp_id = assignments.tmp_id' - ] + 'template_devices' => [ + 'LEFT JOIN', 'template_devices.tmp_id = assignments.tmp_id' + ] ] ); @@ -1291,7 +1290,7 @@ * @throws RangeException */ static function getBannerSettings( $bannerName, $detailed = true ) { - $banner = Banner::fromName( $bannerName ); + $banner = self::fromName( $bannerName ); if ( !$banner->exists() ) { throw new RangeException( "Banner doesn't exist!" ); } @@ -1323,7 +1322,7 @@ * device: device key */ static function getHistoricalBanner( $name, $ts ) { - $id = Banner::fromName( $name )->getId(); + $id = self::fromName( $name )->getId(); $dbr = CNDatabase::getDb(); @@ -1355,10 +1354,10 @@ ], __METHOD__ ); - $banner['display_anon'] = (int) $row->display_anon; - $banner['display_account'] = (int) $row->display_account; + $banner['display_anon'] = (int)$row->display_anon; + $banner['display_account'] = (int)$row->display_account; - $banner['fundraising'] = (int) $row->fundraising; + $banner['fundraising'] = (int)$row->fundraising; $banner['devices'] = [ "desktop" ]; return $banner; @@ -1385,17 +1384,16 @@ $mixins = [], $priorityLangs = [], $devices = null, $summary = null ) { - // Default initial value for devices if ( $devices === null ) { $devices = [ 'desktop' ]; } - if ( $name == '' || !Banner::isValidBannerName( $name ) || $body == '' ) { + if ( $name == '' || !self::isValidBannerName( $name ) || $body == '' ) { return 'centralnotice-null-string'; } - $banner = Banner::newFromName( $name ); + $banner = self::newFromName( $name ); if ( $banner->exists() ) { return 'centralnotice-template-exists'; } @@ -1420,7 +1418,6 @@ * @param string $summary Summary (comment) for this action */ function logBannerChange( $action, $user, $summary = null ) { - ChoiceDataProvider::invalidateCache(); // Summary shouldn't actually come in null, but just in case... @@ -1430,7 +1427,7 @@ $endSettings = []; if ( $action !== 'removed' ) { - $endSettings = Banner::getBannerSettings( $this->getName(), true ); + $endSettings = self::getBannerSettings( $this->getName(), true ); } $dbw = CNDatabase::getDb(); diff --git a/includes/BannerMessage.php b/includes/BannerMessage.php index e53adb8..acc6a83 100644 --- a/includes/BannerMessage.php +++ b/includes/BannerMessage.php @@ -26,7 +26,7 @@ global $wgLanguageCode; if ( $namespace === NS_MEDIAWIKI ) { - return ( $lang === null or $lang === $wgLanguageCode ) ? + return ( $lang === null || $lang === $wgLanguageCode ) ? "Centralnotice-{$this->banner_name}-{$this->name}" : "Centralnotice-{$this->banner_name}-{$this->name}/{$lang}"; } elseif ( $namespace === NS_CN_BANNER ) { @@ -96,7 +96,7 @@ $summary = '/* CN admin */'; } - $savePage = function( $title, $text ) use( $summary ) { + $savePage = function ( $title, $text ) use( $summary ) { $wikiPage = new WikiPage( $title ); $content = ContentHandler::makeContent( $text, $title ); diff --git a/includes/BannerMessageGroup.php b/includes/BannerMessageGroup.php index ef31b6e..46a3442 100644 --- a/includes/BannerMessageGroup.php +++ b/includes/BannerMessageGroup.php @@ -18,7 +18,6 @@ * @param string $title The page name of the CentralNotice banner */ public function __construct( $namespace, $title ) { - $titleObj = Title::makeTitle( $namespace, $title ); $this->id = static::getTranslateGroupName( $title ); @@ -95,7 +94,7 @@ static $useGroupReview = null; if ( $useGroupReview === null ) { - $group = MessageGroups::getGroup( BannerMessageGroup::TRANSLATE_GROUP_NAME_BASE ); + $group = MessageGroups::getGroup( self::TRANSLATE_GROUP_NAME_BASE ); if ( $group && $group->getMessageGroupStates() ) { $useGroupReview = true; } else { @@ -122,11 +121,11 @@ if ( strpos( $bannerName, 'Centralnotice-template' ) === 0 ) { return str_replace( 'Centralnotice-template', - BannerMessageGroup::TRANSLATE_GROUP_NAME_BASE, + self::TRANSLATE_GROUP_NAME_BASE, $bannerName ); } else { - return BannerMessageGroup::TRANSLATE_GROUP_NAME_BASE . '-' . $bannerName; + return self::TRANSLATE_GROUP_NAME_BASE . '-' . $bannerName; } } @@ -147,7 +146,7 @@ global $wgNoticeTranslateDeployStates; // We only need to run this if we're actually using group review - if ( !BannerMessageGroup::isUsingGroupReview() ) { + if ( !self::isUsingGroupReview() ) { return true; } @@ -155,7 +154,7 @@ // Deal with an aggregate group object having changed $groups = $group->getGroups(); foreach ( $groups as $subgroup ) { - BannerMessageGroup::updateBannerGroupStateHook( + self::updateBannerGroupStateHook( $subgroup, $code, $currentState, $newState ); } } elseif ( ( $group instanceof BannerMessageGroup ) @@ -226,7 +225,7 @@ // Create the base aggregate group $conf = []; $conf['BASIC'] = [ - 'id' => BannerMessageGroup::TRANSLATE_GROUP_NAME_BASE, + 'id' => self::TRANSLATE_GROUP_NAME_BASE, 'label' => 'CentralNotice Banners', 'description' => '{{int:centralnotice-aggregate-group-desc}}', 'meta' => 1, @@ -258,21 +257,21 @@ } public static function getLanguagesInState( $banner, $state ) { - if ( !BannerMessageGroup::isUsingGroupReview() ) { + if ( !self::isUsingGroupReview() ) { throw new LogicException( 'CentralNotice is not using group review. Cannot query group review state.' ); } - $groupName = BannerMessageGroup::getTranslateGroupName( $banner ); + $groupName = self::getTranslateGroupName( $banner ); $db = CNDatabase::getDb(); $result = $db->select( 'translate_groupreviews', 'tgr_lang', [ - 'tgr_group' => $groupName, - 'tgr_state' => $state, + 'tgr_group' => $groupName, + 'tgr_state' => $state, ], __METHOD__ ); diff --git a/includes/BannerRenderer.php b/includes/BannerRenderer.php index de3562d..428659d 100644 --- a/includes/BannerRenderer.php +++ b/includes/BannerRenderer.php @@ -102,8 +102,8 @@ $preview = Html::element( 'img', [ - 'src' => $previewUrl, - 'alt' => $bannerName, + 'src' => $previewUrl, + 'alt' => $bannerName, ] ); @@ -113,8 +113,8 @@ $label, $preview, [ - 'class' => 'cn-bannerpreview', - 'id' => Sanitizer::escapeId( "cn-banner-preview-{$this->banner->getName()}" ), + 'class' => 'cn-bannerpreview', + 'id' => Sanitizer::escapeId( "cn-banner-preview-{$this->banner->getName()}" ), ] ); } diff --git a/includes/CNBannerPager.php b/includes/CNBannerPager.php index ec798d6..3872745 100644 --- a/includes/CNBannerPager.php +++ b/includes/CNBannerPager.php @@ -204,7 +204,6 @@ * @see Pager::makeLink() */ public function makeLink( $text, array $query = null, $type = null ) { - $filterQuery = $this->hostSpecialPage->getFilterUrlParamAsArray(); $query = ( $query === null ) ? diff --git a/includes/CNCampaignPager.php b/includes/CNCampaignPager.php index fa3024d..b615a19 100644 --- a/includes/CNCampaignPager.php +++ b/includes/CNCampaignPager.php @@ -28,8 +28,8 @@ * associated with this banner id. */ public function __construct( CentralNotice $onSpecialCN, - $editable = false, $assignedBannerId = null ) { - + $editable = false, $assignedBannerId = null + ) { $this->onSpecialCN = $onSpecialCN; $this->assignedBannerId = $assignedBannerId; $this->editable = $editable; @@ -117,7 +117,6 @@ * @see TablePager::getFieldNames() */ public function getFieldNames() { - if ( !$this->fieldNames ) { $this->fieldNames = [ 'not_name' => $this->msg( 'centralnotice-notice-name' )->text(), @@ -141,7 +140,6 @@ * @see TablePager::getStartBody() */ public function getStartBody() { - $htmlOut = ''; $htmlOut .= Xml::openElement( @@ -167,7 +165,6 @@ } public function formatValue( $fieldName, $value ) { - // These are used in a few cases below. $rowIsEnabled = ( $this->mCurrentRow->not_enabled == '1' ); $rowIsLocked = ( $this->mCurrentRow->not_locked == '1' ); @@ -283,7 +280,6 @@ * @see TablePager::getRowClass() */ public function getRowClass( $row ) { - $enabled = ( $row->not_enabled == '1' ); $archived = ( $row->not_archived == '1' ); @@ -308,7 +304,6 @@ * @see TablePager::getCellAttrs() */ public function getCellAttrs( $field, $value ) { - $attrs = parent::getCellAttrs( $field, $value ); switch ( $field ) { @@ -337,7 +332,6 @@ * @see TablePager::getEndBody() */ public function getEndBody() { - $htmlOut = ''; if ( $this->editable ) { @@ -369,7 +363,6 @@ * @see TablePager::isFieldSortable() */ public function isFieldSortable( $field ) { - // If this is the only page shown, we'll sort via JS, which works on all // columns. if ( $this->isWithinLimit() ) { @@ -410,7 +403,6 @@ * @see IndexPager::extractResultInfo() */ function extractResultInfo( $isFirst, $limit, ResultWrapper $res ) { - parent::extractResultInfo( $isFirst, $limit, $res ); // Disable editing if there's more than one page. (This is a legacy diff --git a/includes/CNChoiceDataResourceLoaderModule.php b/includes/CNChoiceDataResourceLoaderModule.php index c5a013c..cca49e3 100644 --- a/includes/CNChoiceDataResourceLoaderModule.php +++ b/includes/CNChoiceDataResourceLoaderModule.php @@ -34,7 +34,7 @@ return []; } } else { - $choices = ChoiceDataProvider::getChoices( $project, $language ); + $choices = ChoiceDataProvider::getChoices( $project, $language ); } return $choices; @@ -94,7 +94,6 @@ * @see ResourceLoaderModule::getScript() */ public function getScript( ResourceLoaderContext $context ) { - $choices = $this->getChoices( $context ); if ( !$choices ) { // If there are no choices, this module will have no dependencies, @@ -127,8 +126,8 @@ // If this method is called with no context argument (the old method // signature) emit a warning, but don't stop the show. if ( !$context ) { - wfLogWarning( '$context is required for campaign mixins.' ); - return []; + wfLogWarning( '$context is required for campaign mixins.' ); + return []; } // Get the choices (possible campaigns and banners) for this user @@ -142,7 +141,6 @@ $dependencies = []; foreach ( $choices as $choice ) { foreach ( $choice['mixins'] as $mixinName => $mixinParams ) { - if ( !$wgCentralNoticeCampaignMixins[$mixinName]['subscribingModule'] ) { throw new MWException( "No subscribing module for found campaign mixin {$mixinName}" ); diff --git a/includes/CNDatabase.php b/includes/CNDatabase.php index 55f28d4..8355dab 100644 --- a/includes/CNDatabase.php +++ b/includes/CNDatabase.php @@ -40,7 +40,8 @@ // XXX: preventive hack for meandering code if ( ( $target === null ) && - ( $wgRequest->wasPosted() || self::$masterUsedBefore ) ) { + ( $wgRequest->wasPosted() || self::$masterUsedBefore ) + ) { $target = DB_MASTER; } diff --git a/includes/CNDeviceTarget.php b/includes/CNDeviceTarget.php index 2b44a16..6eea8f7 100644 --- a/includes/CNDeviceTarget.php +++ b/includes/CNDeviceTarget.php @@ -55,13 +55,13 @@ $res = $dbr->select( [ - 'tdev' => 'cn_template_devices', - 'devices' => 'cn_known_devices' + 'tdev' => 'cn_template_devices', + 'devices' => 'cn_known_devices' ], [ 'devices.dev_id', 'dev_name' ], [ - 'tdev.tmp_id' => $bannerId, - 'tdev.dev_id = devices.dev_id' + 'tdev.tmp_id' => $bannerId, + 'tdev.dev_id = devices.dev_id' ], __METHOD__ ); @@ -86,8 +86,8 @@ $db->insert( 'cn_known_devices', [ - 'dev_name' => $deviceName, - 'dev_display_label' => $displayLabel + 'dev_name' => $deviceName, + 'dev_display_label' => $displayLabel ], __METHOD__ ); @@ -106,7 +106,7 @@ public static function setBannerDeviceTargets( $bannerId, $newDevices ) { $db = CNDatabase::getDb(); - $knownDevices = CNDeviceTarget::getAvailableDevices( true ); + $knownDevices = self::getAvailableDevices( true ); $newDevices = (array)$newDevices; // Remove all entries from the table for this banner diff --git a/includes/Campaign.php b/includes/Campaign.php index 5402179..38f4f9e 100644 --- a/includes/Campaign.php +++ b/includes/Campaign.php @@ -208,17 +208,17 @@ $row = $db->selectRow( [ 'notices' => 'cn_notices' ], [ - 'not_id', - 'not_name', - 'not_start', - 'not_end', - 'not_enabled', - 'not_preferred', - 'not_locked', - 'not_archived', - 'not_geo', - 'not_buckets', - 'not_throttle', + 'not_id', + 'not_name', + 'not_start', + 'not_end', + 'not_enabled', + 'not_preferred', + 'not_locked', + 'not_archived', + 'not_geo', + 'not_buckets', + 'not_throttle', ], $selector, __METHOD__ @@ -274,7 +274,8 @@ * @return array Array of campaign IDs that matched the filter. */ static function getCampaigns( $project = null, $language = null, $location = null, $date = null, - $enabled = true, $archived = false ) { + $enabled = true, $archived = false + ) { $notices = []; // Database setup @@ -408,9 +409,9 @@ return false; } - $projects = Campaign::getNoticeProjects( $campaignName ); - $languages = Campaign::getNoticeLanguages( $campaignName ); - $geo_countries = Campaign::getNoticeCountries( $campaignName ); + $projects = self::getNoticeProjects( $campaignName ); + $languages = self::getNoticeLanguages( $campaignName ); + $geo_countries = self::getNoticeCountries( $campaignName ); $campaign[ 'projects' ] = implode( ", ", $projects ); $campaign[ 'languages' ] = implode( ", ", $languages ); $campaign[ 'countries' ] = implode( ", ", $geo_countries ); @@ -426,7 +427,7 @@ // Encode into a JSON string for storage $campaign[ 'banners' ] = FormatJson::encode( $bannersOut ); $campaign[ 'mixins' ] = - FormatJson::encode( Campaign::getCampaignMixins( $campaignName, true ) ); + FormatJson::encode( self::getCampaignMixins( $campaignName, true ) ); return $campaign; } @@ -565,7 +566,6 @@ * @return array */ public static function getCampaignMixins( $campaignName, $compact = false ) { - global $wgCentralNoticeCampaignMixins; $dbr = CNDatabase::getDb(); @@ -608,7 +608,6 @@ // parameters). $campaignMixins = []; foreach ( $dbRows as $dbRow ) { - $mixinName = $dbRow->nmxn_mixin_name; // A mixin may have been removed from the code but may still @@ -619,14 +618,13 @@ // First time we have a result row for this mixin? if ( !isset( $campaignMixins[$mixinName] ) ) { - // Data structure depends on $compact if ( $compact ) { $campaignMixins[$mixinName] = []; } else { $campaignMixins[$mixinName] = [ - 'enabled' => (bool) $dbRow->nmxn_enabled, + 'enabled' => (bool)$dbRow->nmxn_enabled, 'parameters' => [] ]; } @@ -634,7 +632,6 @@ // If there are mixin params in this row, add them in if ( !is_null( $dbRow->nmxnp_param_name ) ) { - $paramName = $dbRow->nmxnp_param_name; $mixinDef = $wgCentralNoticeCampaignMixins[$mixinName]; @@ -684,7 +681,7 @@ } // Again, data structure depends on $compact - if ( $compact ) { + if ( $compact ) { $campaignMixins[$mixinName][$paramName] = $paramVal; } else { $campaignMixins[$mixinName]['parameters'][$paramName] @@ -716,8 +713,8 @@ * @param array $params For mixins with no parameters, set to an empty array. */ public static function updateCampaignMixins( - $campaignName, $mixinName, $enable, $params = null ) { - + $campaignName, $mixinName, $enable, $params = null + ) { global $wgCentralNoticeCampaignMixins; // TODO Error handling! @@ -731,7 +728,6 @@ [ 'not_name' => $campaignName ] )->not_id; if ( $enable ) { - if ( $params === null ) { throw new InvalidArgumentException( 'Paremeters info required to enable mixin ' . $mixinName . ' for campaign '. $campaignName ); @@ -760,13 +756,11 @@ )->nmxn_id; foreach ( $params as $paramName => $paramVal ) { - $mixinDef = $wgCentralNoticeCampaignMixins[$mixinName]; // Handle an undefined parameter. Not likely to happen, maybe // in the middle of a deploy that removes a parameter. if ( !isset( $mixinDef['parameters'][$paramName] ) ) { - wfLogWarning( 'No definition found for the parameter ' . $paramName . ' for the campaign mixn ' . $mixinName . '.' ); @@ -849,7 +843,7 @@ $user, $summary = null ) { $noticeName = trim( $noticeName ); - if ( Campaign::campaignExists( $noticeName ) ) { + if ( self::campaignExists( $noticeName ) ) { return 'centralnotice-notice-exists'; } elseif ( empty( $projects ) ) { return 'centralnotice-no-project'; @@ -922,7 +916,7 @@ 'geo' => (int)$geotargeted, 'throttle' => $throttle, ]; - Campaign::logCampaignChange( 'created', $not_id, $user, + self::logCampaignChange( 'created', $not_id, $user, $beginSettings, $endSettings, $summary ); return $not_id; @@ -954,15 +948,15 @@ return 'centralnotice-notice-is-locked'; } - Campaign::removeCampaignByName( $campaignName, $user ); + self::removeCampaignByName( $campaignName, $user ); return true; } private static function removeCampaignByName( $campaignName, $user ) { // Log the removal of the campaign - $campaignId = Campaign::getNoticeId( $campaignName ); - Campaign::logCampaignChange( 'removed', $campaignId, $user ); + $campaignId = self::getNoticeId( $campaignName ); + self::logCampaignChange( 'removed', $campaignId, $user ); $dbw = CNDatabase::getDb( DB_MASTER ); $dbw->startAtomic( __METHOD__ ); @@ -986,7 +980,7 @@ $dbw = CNDatabase::getDb( DB_MASTER ); $eNoticeName = htmlspecialchars( $noticeName ); - $noticeId = Campaign::getNoticeId( $eNoticeName ); + $noticeId = self::getNoticeId( $eNoticeName ); $templateId = Banner::fromName( $templateName )->getId(); $res = $dbw->select( 'cn_assignments', 'asn_id', [ @@ -999,7 +993,7 @@ return 'centralnotice-template-already-exists'; } - $noticeId = Campaign::getNoticeId( $eNoticeName ); + $noticeId = self::getNoticeId( $eNoticeName ); $dbw->insert( 'cn_assignments', [ 'tmp_id' => $templateId, @@ -1017,7 +1011,7 @@ */ static function removeTemplateFor( $noticeName, $templateName ) { $dbw = CNDatabase::getDb( DB_MASTER ); - $noticeId = Campaign::getNoticeId( $noticeName ); + $noticeId = self::getNoticeId( $noticeName ); $templateId = Banner::fromName( $templateName )->getId(); $dbw->delete( 'cn_assignments', [ 'tmp_id' => $templateId, 'not_id' => $noticeId ] ); } @@ -1115,7 +1109,7 @@ } // Invalid campaign name - if ( !Campaign::campaignExists( $noticeName ) ) { + if ( !self::campaignExists( $noticeName ) ) { return 'centralnotice-notice-doesnt-exist'; } @@ -1142,7 +1136,7 @@ * @param $settingValue bool: Value to use for the setting, true or false */ static function setBooleanCampaignSetting( $noticeName, $settingName, $settingValue ) { - if ( !Campaign::campaignExists( $noticeName ) ) { + if ( !self::campaignExists( $noticeName ) ) { // Exit quietly since campaign may have been deleted at the same time. return; } else { @@ -1184,7 +1178,7 @@ $settingValue = $min; } - if ( !Campaign::campaignExists( $noticeName ) ) { + if ( !self::campaignExists( $noticeName ) ) { // Exit quietly since campaign may have been deleted at the same time. return; } else { @@ -1206,7 +1200,7 @@ */ static function updateWeight( $noticeName, $templateId, $weight ) { $dbw = CNDatabase::getDb( DB_MASTER ); - $noticeId = Campaign::getNoticeId( $noticeName ); + $noticeId = self::getNoticeId( $noticeName ); $dbw->update( 'cn_assignments', [ 'tmp_weight' => $weight ], [ @@ -1226,7 +1220,7 @@ */ static function updateBucket( $noticeName, $templateId, $bucket ) { $dbw = CNDatabase::getDb( DB_MASTER ); - $noticeId = Campaign::getNoticeId( $noticeName ); + $noticeId = self::getNoticeId( $noticeName ); $dbw->update( 'cn_assignments', [ 'asn_bucket' => $bucket ], [ @@ -1252,7 +1246,7 @@ $dbw->startAtomic( __METHOD__ ); // Get the previously assigned projects - $oldProjects = Campaign::getNoticeProjects( $notice ); + $oldProjects = self::getNoticeProjects( $notice ); // Get the notice id $row = $dbw->selectRow( 'cn_notices', 'not_id', [ 'not_name' => $notice ] ); @@ -1281,7 +1275,7 @@ $dbw->startAtomic( __METHOD__ ); // Get the previously assigned languages - $oldLanguages = Campaign::getNoticeLanguages( $notice ); + $oldLanguages = self::getNoticeLanguages( $notice ); // Get the notice id $row = $dbw->selectRow( 'cn_notices', 'not_id', [ 'not_name' => $notice ] ); @@ -1310,7 +1304,7 @@ $dbw->startAtomic( __METHOD__ ); // Get the previously assigned languages - $oldCountries = Campaign::getNoticeCountries( $notice ); + $oldCountries = self::getNoticeCountries( $notice ); // Get the notice id $row = $dbw->selectRow( 'cn_notices', 'not_id', [ 'not_name' => $notice ] ); @@ -1366,7 +1360,7 @@ 'notlog_user_id' => $user->getId(), 'notlog_action' => $action, 'notlog_not_id' => $campaignId, - 'notlog_not_name' => Campaign::getNoticeName( $campaignId ), + 'notlog_not_name' => self::getNoticeName( $campaignId ), 'notlog_comment' => $summary, ]; @@ -1386,7 +1380,7 @@ } static function campaignLogs( - $campaign=false, $username=false, $start=false, $end=false, $limit=50, $offset=0 + $campaign = false, $username = false, $start = false, $end = false, $limit = 50, $offset = 0 ) { $conds = []; if ( $start ) { diff --git a/includes/CampaignLog.php b/includes/CampaignLog.php index 47c7c2e..e47a5a3 100644 --- a/includes/CampaignLog.php +++ b/includes/CampaignLog.php @@ -14,20 +14,20 @@ $begin = []; $end = []; if ( $row ) { - $comma_explode = function( $str ) { + $comma_explode = function ( $str ) { return explode( ", ", $str ); }; - $json_decode = function( $json ) { + $json_decode = function ( $json ) { return json_decode( $json, true ); }; - $store = function( $name, $decode = null ) use ( $row, &$begin, &$end ) { + $store = function ( $name, $decode = null ) use ( $row, &$begin, &$end ) { $beginField = 'notlog_begin_' . $name; $endField = 'notlog_end_' . $name; if ( !$decode ) { - $decode = function( $v ) { + $decode = function ( $v ) { return $v; }; } @@ -68,7 +68,7 @@ $begin =& $this->begin; $end =& $this->end; - $diff_basic = function( $name ) use ( &$removed, &$added, &$begin, &$end ) { + $diff_basic = function ( $name ) use ( &$removed, &$added, &$begin, &$end ) { if ( $begin[ $name ] !== $end[ $name ] ) { if ( $begin[ $name ] !== null ) { $removed[ $name ] = $begin[ $name ]; @@ -78,7 +78,7 @@ } } }; - $diff_list = function( $name ) use ( &$removed, &$added, &$begin, &$end ) { + $diff_list = function ( $name ) use ( &$removed, &$added, &$begin, &$end ) { if ( $begin[ $name ] !== $end[ $name ] ) { $removed[ $name ] = array_diff( $begin[ $name ], $end[ $name ] ); if ( !$removed[ $name ] || $removed[ $name ] === [ "" ] ) { @@ -90,7 +90,7 @@ } } }; - $diff_map = function( $name ) use ( &$removed, &$added, &$begin, &$end ) { + $diff_map = function ( $name ) use ( &$removed, &$added, &$begin, &$end ) { $removed[ $name ] = $begin[ $name ]; $added[ $name ] = $end[ $name ]; diff --git a/includes/CdnCacheUpdateBannerLoader.php b/includes/CdnCacheUpdateBannerLoader.php index c3fc173..7f5ec26 100644 --- a/includes/CdnCacheUpdateBannerLoader.php +++ b/includes/CdnCacheUpdateBannerLoader.php @@ -27,7 +27,6 @@ * Purges the banner loader URls for the language and banner passed to the constructor. */ public function doUpdate() { - global $wgCentralSelectedBannerDispatcher, $wgCentralSelectedMobileBannerDispatcher; @@ -55,7 +54,6 @@ $campaignNames = $this->banner->getCampaignNames(); foreach ( $campaignNames as $campaignName ) { - $paramPerms[] = [ 'campaign' => $campaignName, 'banner' => $bannerName, @@ -80,7 +78,6 @@ // Create the full URLs $urlsToPurge = []; foreach ( $paramPerms as $params ) { - $urlsToPurge[] = wfAppendQuery( $wgCentralSelectedBannerDispatcher, $params diff --git a/includes/ChoiceDataProvider.php b/includes/ChoiceDataProvider.php index 78b2a86..ca37a6f 100644 --- a/includes/ChoiceDataProvider.php +++ b/includes/ChoiceDataProvider.php @@ -43,7 +43,6 @@ self::CACHE_TTL, function ( $oldValue, &$ttl, array &$setOpts ) use ( $project, $language ) { - $dbr = CNDatabase::getDb( DB_SLAVE ); // Account for slave lag to prevent a race condition when @@ -75,8 +74,8 @@ } private static function fetchChoices( $project, $language, - IDatabase $dbr ) { - + IDatabase $dbr + ) { // For speed, we'll do our own queries instead of using methods in // Campaign and Banner. @@ -149,7 +148,6 @@ $assignmentKeysByBannerIdAndCampaignId = []; foreach ( $dbRows as $dbRow ) { - $campaignId = $dbRow->not_id; $campaignName = $dbRow->not_name; $bannerId = $dbRow->tmp_id; @@ -176,7 +174,7 @@ 'preferred' => intval( $dbRow->not_preferred ), 'throttle' => intval( $dbRow->not_throttle ), 'bucket_count' => intval( $dbRow->not_buckets ), - 'geotargeted' => (bool) $dbRow->not_geo, + 'geotargeted' => (bool)$dbRow->not_geo, 'banners' => [] ]; } @@ -190,8 +188,8 @@ 'bucket' => intval( $bucket ), 'weight' => intval( $dbRow->tmp_weight ), 'category' => $category, - 'display_anon' => (bool) $dbRow->tmp_display_anon, - 'display_account' => (bool) $dbRow->tmp_display_account, + 'display_anon' => (bool)$dbRow->tmp_display_anon, + 'display_account' => (bool)$dbRow->tmp_display_account, 'devices' => [] // To be filled by the last query ]; @@ -246,7 +244,6 @@ // Add campaign-associated mixins to the data structure foreach ( $choices as &$campaignInfo ) { - // Get info for enabled mixins for this campaign $campaignInfo['mixins'] = Campaign::getCampaignMixins( $campaignInfo['name'], true ); @@ -276,7 +273,6 @@ // Add devices to the data structure. foreach ( $dbRows as $dbRow ) { - $bannerId = $dbRow->tmp_id; // Traverse the data structure to add in devices @@ -285,8 +281,8 @@ $assignmentKeysByBannerIdAndCampaignId[$bannerId]; foreach ( $assignmentKeysByCampaignId - as $campaignId => $assignmentKeys ) { - + as $campaignId => $assignmentKeys + ) { foreach ( $assignmentKeys as $assignmentKey ) { $choices[$campaignId]['banners'][$assignmentKey]['devices'][] = $dbRow->dev_name; @@ -311,7 +307,7 @@ return $b; }; - $compareNames = function( $a, $b ) { + $compareNames = function ( $a, $b ) { if ( $a['name'] == $b['name'] ) { return 0; } @@ -319,7 +315,6 @@ }; $fixCampaignPropsFn = function ( $c ) use ( $uniqueDevFn, $compareNames ) { - $c['banners'] = array_map( $uniqueDevFn, array_values( $c['banners'] ) ); usort( $c['banners'], $compareNames ); diff --git a/includes/HtmlFormElements/HTMLCentralNoticeBanner.php b/includes/HtmlFormElements/HTMLCentralNoticeBanner.php index 4582e6a..00fe5ec 100644 --- a/includes/HtmlFormElements/HTMLCentralNoticeBanner.php +++ b/includes/HtmlFormElements/HTMLCentralNoticeBanner.php @@ -62,8 +62,8 @@ return Xml::tags( 'div', [ - 'id' => Sanitizer::escapeId( "cn-banner-preview-$bannerName" ), - 'class' => 'cn-banner-preview-div', + 'id' => Sanitizer::escapeId( "cn-banner-preview-$bannerName" ), + 'class' => 'cn-banner-preview-div', ], $preview ); @@ -94,8 +94,8 @@ $html = Xml::openElement( 'div', [ - 'id' => Sanitizer::escapeId( "cn-banner-list-element-{$this->mParams['banner']}" ), - 'class' => "cn-banner-list-element", + 'id' => Sanitizer::escapeId( "cn-banner-list-element-{$this->mParams['banner']}" ), + 'class' => "cn-banner-list-element", ] ); @@ -114,9 +114,9 @@ $this->msg( 'centralnotice-live-preview' ), [ 'class' => 'cn-banner-list-element-label-text' ], [ - 'banner' => $bannerName, - 'uselang' => $language, - 'force' => '1' + 'banner' => $bannerName, + 'uselang' => $language, + 'force' => '1' ] ) . ')'; // TODO: Output status icons diff --git a/patches/CNDatabasePatcher.php b/patches/CNDatabasePatcher.php index ff7dd63..d750b98 100644 --- a/patches/CNDatabasePatcher.php +++ b/patches/CNDatabasePatcher.php @@ -23,104 +23,104 @@ if ( $updater->getDB()->getType() == 'mysql' ) { $updater->addExtensionUpdate( [ - 'addTable', 'cn_notices', - $base . '/../CentralNotice.sql', true + 'addTable', 'cn_notices', + $base . '/../CentralNotice.sql', true ] ); $updater->addExtensionUpdate( [ - 'addField', 'cn_notices', 'not_preferred', - $base . '/patch-notice_preferred.sql', true + 'addField', 'cn_notices', 'not_preferred', + $base . '/patch-notice_preferred.sql', true ] ); $updater->addExtensionUpdate( [ - 'addTable', 'cn_notice_languages', - $base . '/patch-notice_languages.sql', true + 'addTable', 'cn_notice_languages', + $base . '/patch-notice_languages.sql', true ] ); $updater->addExtensionUpdate( [ - 'addField', 'cn_templates', 'tmp_display_anon', - $base . '/patch-template_settings.sql', true + 'addField', 'cn_templates', 'tmp_display_anon', + $base . '/patch-template_settings.sql', true ] ); $updater->addExtensionUpdate( [ - 'addField', 'cn_templates', 'tmp_fundraising', - $base . '/patch-template_fundraising.sql', true + 'addField', 'cn_templates', 'tmp_fundraising', + $base . '/patch-template_fundraising.sql', true ] ); $updater->addExtensionUpdate( [ - 'addTable', 'cn_notice_countries', - $base . '/patch-notice_countries.sql', true + 'addTable', 'cn_notice_countries', + $base . '/patch-notice_countries.sql', true ] ); $updater->addExtensionUpdate( [ - 'addTable', 'cn_notice_projects', - $base . '/patch-notice_projects.sql', true + 'addTable', 'cn_notice_projects', + $base . '/patch-notice_projects.sql', true ] ); $updater->addExtensionUpdate( [ - 'addTable', 'cn_notice_log', - $base . '/patch-notice_log.sql', true + 'addTable', 'cn_notice_log', + $base . '/patch-notice_log.sql', true ] ); $updater->addExtensionUpdate( [ - 'addTable', 'cn_template_log', - $base . '/patch-template_log.sql', true + 'addTable', 'cn_template_log', + $base . '/patch-template_log.sql', true ] ); $updater->addExtensionUpdate( [ - 'addField', 'cn_templates', 'tmp_autolink', - $base . '/patch-template_autolink.sql', true + 'addField', 'cn_templates', 'tmp_autolink', + $base . '/patch-template_autolink.sql', true ] ); $updater->addExtensionUpdate( [ - 'addField', 'cn_template_log', 'tmplog_begin_prioritylangs', - $base . '/patch-prioritylangs.sql', true + 'addField', 'cn_template_log', 'tmplog_begin_prioritylangs', + $base . '/patch-prioritylangs.sql', true ] ); $updater->addExtensionUpdate( [ - 'addField', 'cn_notices', 'not_buckets', - $base . '/patch-bucketing.sql', true + 'addField', 'cn_notices', 'not_buckets', + $base . '/patch-bucketing.sql', true ] ); $updater->addExtensionUpdate( [ - 'addTable', 'cn_template_mixins', - $base . '/patch-centralnotice-2_3.sql', true + 'addTable', 'cn_template_mixins', + $base . '/patch-centralnotice-2_3.sql', true ] ); $updater->addExtensionUpdate( [ - 'addField', 'cn_template_mixins', 'mixin_name', - $base . '/patch-mixin_modules.sql', true + 'addField', 'cn_template_mixins', 'mixin_name', + $base . '/patch-mixin_modules.sql', true ] ); $updater->addExtensionUpdate( [ - 'addField', 'cn_template_log', 'tmplog_begin_devices', - $base . '/patch-template-device-logging.sql', true + 'addField', 'cn_template_log', 'tmplog_begin_devices', + $base . '/patch-template-device-logging.sql', true ] ); $updater->addExtensionUpdate( [ - 'addIndex', 'cn_templates', 'tmp_category', - $base . '/patch-custom-groups.sql', true + 'addIndex', 'cn_templates', 'tmp_category', + $base . '/patch-custom-groups.sql', true ] ); $updater->addExtensionUpdate( [ - 'addField', 'cn_notices', 'not_throttle', - $base . '/patch-campaign_throttle.sql', true + 'addField', 'cn_notices', 'not_throttle', + $base . '/patch-campaign_throttle.sql', true ] ); $updater->addExtensionUpdate( @@ -132,39 +132,39 @@ ); $updater->addExtensionUpdate( [ - 'addField', 'cn_template_log', 'tmplog_comment', - $base . '/patch-template-logging-comments.sql', true + 'addField', 'cn_template_log', 'tmplog_comment', + $base . '/patch-template-logging-comments.sql', true ] ); $updater->addExtensionUpdate( [ - 'addField', 'cn_notice_log', 'notlog_comment', - $base . '/patch-notice-logging-comments.sql', true + 'addField', 'cn_notice_log', 'notlog_comment', + $base . '/patch-notice-logging-comments.sql', true ] ); $updater->addExtensionUpdate( [ - 'addIndex', 'cn_assignments', 'asn_bucket', - $base . '/patch-assignments_index.sql', true + 'addIndex', 'cn_assignments', 'asn_bucket', + $base . '/patch-assignments_index.sql', true ] ); $updater->addExtensionUpdate( [ - 'addTable', 'cn_notice_mixins', - $base . '/patch-notice-mixins.sql', true + 'addTable', 'cn_notice_mixins', + $base . '/patch-notice-mixins.sql', true ] ); $updater->addExtensionUpdate( [ - 'addTable', 'cn_notice_mixin_params', - $base . '/patch-notice-mixins-params.sql', true + 'addTable', 'cn_notice_mixin_params', + $base . '/patch-notice-mixins-params.sql', true ] ); // This adds both notlog_begin_mixins and notlog_end_mixins fields $updater->addExtensionUpdate( [ - 'addField', 'cn_notice_log', 'notlog_begin_mixins', - $base . '/patch-notice-mixins-log.sql', true + 'addField', 'cn_notice_log', 'notlog_begin_mixins', + $base . '/patch-notice-mixins-log.sql', true ] ); } elseif ( $updater->getDB()->getType() == 'sqlite' ) { diff --git a/phpcs.xml b/phpcs.xml index 0a4d45a..c74d82f 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -1,9 +1,10 @@ <?xml version="1.0" encoding="UTF-8"?> <ruleset> - <rule ref="./vendor/mediawiki/mediawiki-codesniffer/MediaWiki"/> + <rule ref="./vendor/mediawiki/mediawiki-codesniffer/MediaWiki"> + <exclude name="MediaWiki.WhiteSpace.SpaceBeforeSingleLineComment.NewLineComment"/> + <exclude name="MediaWiki.Commenting.FunctionComment"/> + </rule> <file>.</file> <arg name="extensions" value="php,php5,inc"/> <arg name="encoding" value="UTF-8"/> - <exclude-pattern>vendor</exclude-pattern> - <exclude-pattern>node_modules</exclude-pattern> </ruleset> diff --git a/special/SpecialBannerAllocation.php b/special/SpecialBannerAllocation.php index bb37a0e..996fef1 100644 --- a/special/SpecialBannerAllocation.php +++ b/special/SpecialBannerAllocation.php @@ -77,7 +77,7 @@ $this->location = $locationSubmitted ? $locationSubmitted : $this->location; // Convert submitted location to boolean value. If it true, showList() will be called. - $locationSubmitted = (boolean) $locationSubmitted; + $locationSubmitted = (bool)$locationSubmitted; // Begin output $this->setHeaders(); @@ -213,8 +213,8 @@ $htmlOut .= Html::openElement( 'div', [ - 'id' => "cn-allocation-{$project}-{$language}-{$country}-{$deviceId}", - 'class' => 'cn-allocation-group' + 'id' => "cn-allocation-{$project}-{$language}-{$country}-{$deviceId}", + 'class' => 'cn-allocation-group' ] ); diff --git a/special/SpecialBannerLoader.php b/special/SpecialBannerLoader.php index e48aa65..7c5b34c 100644 --- a/special/SpecialBannerLoader.php +++ b/special/SpecialBannerLoader.php @@ -25,7 +25,6 @@ } function execute( $par ) { - $this->getOutput()->disable(); try { @@ -90,7 +89,6 @@ header( "Content-type: $wgJsMimeType; charset=utf-8" ); if ( !$this->getUser()->isLoggedIn() ) { - // This header tells our front-end caches to retain the content for // $sMaxAge seconds. $sMaxAge = ( $cacheResponse === self::MAX_CACHE_NORMAL ) ? @@ -188,7 +186,6 @@ */ class BannerLoaderException extends Exception { function __construct( $bannerName = '(none provided)', $extraMsg = null ) { - $this->message = get_called_class() . " while loading banner: '{$bannerName}'"; if ( $extraMsg ) { diff --git a/special/SpecialCNReporter.php b/special/SpecialCNReporter.php index 242076b..876d724 100644 --- a/special/SpecialCNReporter.php +++ b/special/SpecialCNReporter.php @@ -33,7 +33,6 @@ </script></body></html> EOT; print $script; - } /** diff --git a/special/SpecialCentralNotice.php b/special/SpecialCentralNotice.php index 037557e..88f56de 100644 --- a/special/SpecialCentralNotice.php +++ b/special/SpecialCentralNotice.php @@ -66,7 +66,6 @@ // Check authentication token if ( $this->getUser()->matchEditToken( $request->getVal( 'authtoken' ) ) ) { - // Handle adding a campaign or changing existing campaign settings // via the list interface. In either case, we'll retirect to the // list view. @@ -108,7 +107,6 @@ * the "Add campaign" form. */ protected function outputListOfNotices() { - $this->outputEnclosingDivStartTag(); $out = $this->getOutput(); @@ -132,19 +130,16 @@ } protected function handleNoticePostFromList() { - $request = $this->getRequest(); $changes = json_decode( $request->getText( 'changes' ), true ); $summary = $this->getSummaryFromRequest( $request ); // Make the changes requested foreach ( $changes as $campaignName => $campaignChanges ) { - $initialSettings = Campaign::getCampaignSettings( $campaignName ); // Next campaign if somehow this one doesn't exist if ( !$initialSettings ) { - wfLogWarning( 'Change requested for non-existent campaign ' . $campaignName ); @@ -153,31 +148,27 @@ // Set values as per $changes if ( isset( $campaignChanges['archived'] ) ) { - Campaign::setBooleanCampaignSetting( $campaignName, 'archived', $campaignChanges['archived'] ); } if ( isset( $campaignChanges['locked'] ) ) { - Campaign::setBooleanCampaignSetting( $campaignName, 'locked', $campaignChanges['locked'] ); } if ( isset( $campaignChanges['enabled'] ) ) { - Campaign::setBooleanCampaignSetting( $campaignName, 'enabled', $campaignChanges['enabled'] ); } if ( isset( $campaignChanges['priority'] ) ) { - Campaign::setNumericCampaignSetting( $campaignName, 'preferred', intval( $campaignChanges['priority'] ), - CentralNotice::EMERGENCY_PRIORITY, - CentralNotice::LOW_PRIORITY + self::EMERGENCY_PRIORITY, + self::LOW_PRIORITY ); } @@ -275,16 +266,15 @@ */ public function prioritySelector( $index, $editable, $priorityValue ) { $priorities = [ - CentralNotice::LOW_PRIORITY => wfMessage( 'centralnotice-priority-low' )->escaped(), - CentralNotice::NORMAL_PRIORITY => + self::LOW_PRIORITY => wfMessage( 'centralnotice-priority-low' )->escaped(), + self::NORMAL_PRIORITY => wfMessage( 'centralnotice-priority-normal' )->escaped(), - CentralNotice::HIGH_PRIORITY => wfMessage( 'centralnotice-priority-high' )->escaped(), - CentralNotice::EMERGENCY_PRIORITY => + self::HIGH_PRIORITY => wfMessage( 'centralnotice-priority-high' )->escaped(), + self::EMERGENCY_PRIORITY => wfMessage( 'centralnotice-priority-emergency' )->escaped(), ]; if ( $editable ) { - $options = ''; // The HTML for the select list options foreach ( $priorities as $key => $label ) { $options .= Xml::option( $label, $key, $priorityValue == $key ); @@ -324,7 +314,7 @@ foreach ( $fields as $data ) { list( $field, $label, $set, $current ) = $data; $out .= Xml::listDropDown( "{$prefix}[{$field}]", - CentralNotice::dropDownList( $this->msg( $label )->text(), $set ), + self::dropDownList( $this->msg( $label )->text(), $set ), '', $current ); } @@ -401,7 +391,7 @@ Xml::check( 'geotargeted', false, [ 'value' => 1, 'id' => 'geotargeted' ] ) ); $htmlOut .= Xml::closeElement( 'tr' ); $htmlOut .= Xml::openElement( 'tr', - [ 'id'=> 'geoMultiSelector', 'style'=> 'display:none;' ] ); + [ 'id' => 'geoMultiSelector', 'style' => 'display:none;' ] ); $htmlOut .= Xml::tags( 'td', [ 'valign' => 'top' ], $this->msg( 'centralnotice-countries' )->escaped() ); $htmlOut .= Xml::tags( 'td', [], $this->geoMultiSelector() ); @@ -440,7 +430,7 @@ } else { $result = Campaign::addCampaign( $noticeName, false, $start, $projects, $project_languages, $geotargeted, $geo_countries, - 100, CentralNotice::NORMAL_PRIORITY, $this->getUser(), + 100, self::NORMAL_PRIORITY, $this->getUser(), $this->getSummaryFromRequest( $request ) ); if ( is_string( $result ) ) { // TODO Better error handling @@ -594,10 +584,8 @@ // filter); process the request. Recall that if the serious request // succeeds, the page will be reloaded again. if ( $request->getCheck( 'template-search' ) == false ) { - // Check authentication token if ( $this->getUser()->matchEditToken( $request->getVal( 'authtoken' ) ) ) { - // Handle removing campaign if ( $request->getVal( 'archive' ) ) { Campaign::setBooleanCampaignSetting( $notice, 'archived', true ); @@ -640,9 +628,9 @@ Campaign::setNumericCampaignSetting( $notice, 'preferred', - $request->getInt( 'priority', CentralNotice::NORMAL_PRIORITY ), - CentralNotice::EMERGENCY_PRIORITY, - CentralNotice::LOW_PRIORITY + $request->getInt( 'priority', self::NORMAL_PRIORITY ), + self::EMERGENCY_PRIORITY, + self::LOW_PRIORITY ); // Handle updating geotargeting @@ -728,15 +716,12 @@ foreach ( $wgCentralNoticeCampaignMixins as $mixinName => $mixinDef ) { - $mixinControlName = self::makeNoticeMixinControlName( $mixinName ); if ( $request->getCheck( $mixinControlName ) ) { - $params = []; foreach ( $mixinDef['parameters'] as $paramName => $paramDef ) { - $requestParamName = self::makeNoticeMixinControlName( $mixinName, $paramName ); @@ -833,7 +818,7 @@ $start = $this->getDateTime( 'start' ); $end = $this->getDateTime( 'end' ); $isEnabled = $request->getCheck( 'enabled' ); - $priority = $request->getInt( 'priority', CentralNotice::NORMAL_PRIORITY ); + $priority = $request->getInt( 'priority', self::NORMAL_PRIORITY ); $throttle = $request->getInt( 'throttle', 100 ); $isLocked = $request->getCheck( 'locked' ); $isArchived = $request->getCheck( 'archived' ); @@ -910,7 +895,7 @@ $readonly, [ 'value' => $notice, 'id' => 'geotargeted' ] ) ) ); $htmlOut .= Xml::closeElement( 'tr' ); - $htmlOut .= Xml::openElement( 'tr', [ 'id'=> 'geoMultiSelector' ] ); + $htmlOut .= Xml::openElement( 'tr', [ 'id' => 'geoMultiSelector' ] ); $htmlOut .= Xml::tags( 'td', [ 'valign' => 'top' ], $this->msg( 'centralnotice-countries' )->escaped() ); $htmlOut .= Xml::tags( 'td', [], $this->geoMultiSelector( $countries ) ); @@ -987,7 +972,6 @@ // Create controls for campaign-associated mixins (if there are any) if ( !empty( $wgCentralNoticeCampaignMixins ) ) { - $mixinsThisNotice = Campaign::getCampaignMixins( $notice ); $htmlOut .= Xml::fieldset( @@ -995,7 +979,6 @@ foreach ( $wgCentralNoticeCampaignMixins as $mixinName => $mixinDef ) { - $mixinControlName = self::makeNoticeMixinControlName( $mixinName ); $attribs = [ @@ -1006,7 +989,6 @@ ]; if ( isset( $mixinsThisNotice[$mixinName] ) ) { - // We have data on the mixin for this campaign, though // it may not have been enabled. @@ -1059,8 +1041,8 @@ } protected static function makeNoticeMixinControlName( - $mixinName, $mixinParam=null ) { - + $mixinName, $mixinParam = null + ) { return 'notice-mixin-' . $mixinName . ( $mixinParam ? '-' . $mixinParam : '' ); } @@ -1331,8 +1313,8 @@ $htmlOut .= Html::element( 'input', [ - 'type'=> 'submit', - 'name'=> 'template-search', + 'type' => 'submit', + 'name' => 'template-search', 'value' => $this->msg( 'centralnotice-filter-template-submit' )->text() ] ); @@ -1341,7 +1323,6 @@ // And now the banners, if any if ( $pager->getNumRows() > 0 ) { - // Show paginated list of banners $htmlOut .= Xml::tags( 'div', [ 'class' => 'cn-pager' ], @@ -1449,7 +1430,6 @@ * @return string */ public function makeSummaryField( $action = false ) { - $placeholderMsg = $action ? 'centralnotice-change-summary-action-prompt' : 'centralnotice-change-summary-prompt'; diff --git a/special/SpecialCentralNoticeBanners.php b/special/SpecialCentralNoticeBanners.php index b6ccbd0..d76a454 100644 --- a/special/SpecialCentralNoticeBanners.php +++ b/special/SpecialCentralNoticeBanners.php @@ -214,11 +214,11 @@ $this, 'banner-list', [ - 'applyTo' => [ - 'section' => 'banner-list', - 'class' => 'HTMLCheckField', - 'cssclass' => 'cn-bannerlist-check-applyto', - ] + 'applyTo' => [ + 'section' => 'banner-list', + 'class' => 'HTMLCheckField', + 'cssclass' => 'cn-bannerlist-check-applyto', + ] ], [], $filter, @@ -240,7 +240,6 @@ * @return null|string|array */ public function processBannerList( $formData ) { - $this->setFilterFromUrl(); if ( $formData[ 'action' ] && $this->editable ) { @@ -329,7 +328,6 @@ * Use a URL parameter to set the filter string for the banner list. */ protected function setFilterFromUrl() { - // This is the normal param on visible URLs. $filterParam = $this->getRequest()->getVal( 'filter', null ); @@ -353,7 +351,6 @@ * @return array */ public function getFilterUrlParamAsArray() { - return $this->bannerFilterString ? [ 'filter' => $this->bannerFilterString ] : []; } @@ -371,9 +368,9 @@ $this->msg( 'centralnotice-live-preview' )->escaped(), [ 'class' => 'cn-banner-list-element-label-text' ], [ - 'banner' => $this->bannerName, - 'uselang' => $this->bannerLanguagePreview, - 'force' => '1', + 'banner' => $this->bannerName, + 'uselang' => $this->bannerLanguagePreview, + 'force' => '1', ] ) ]; @@ -457,7 +454,7 @@ $languages = Language::fetchLanguageNames( $this->getLanguage()->getCode() ); array_walk( $languages, - function( &$val, $index ) { + function ( &$val, $index ) { $val = "$index - $val"; } ); @@ -490,7 +487,7 @@ 'help-message' => 'centralnotice-banner-class-desc', 'options' => Banner::getAllUsedCategories(), 'size' => 30, - 'maxlength'=> 255, + 'maxlength' => 255, 'default' => $banner->getCategory(), ]; diff --git a/special/SpecialCentralNoticeLogs.php b/special/SpecialCentralNoticeLogs.php index 9720977..f55c1e2 100644 --- a/special/SpecialCentralNoticeLogs.php +++ b/special/SpecialCentralNoticeLogs.php @@ -64,7 +64,6 @@ $htmlOut .= Xml::closeElement( 'div' ); if ( $this->logType == 'campaignsettings' ) { - $reset = $request->getVal( 'centralnoticelogreset' ); $campaign = $request->getVal( 'campaign' ); $user = $request->getVal( 'user' ); diff --git a/special/SpecialGlobalAllocation.php b/special/SpecialGlobalAllocation.php index 70f1da2..7c430d9 100644 --- a/special/SpecialGlobalAllocation.php +++ b/special/SpecialGlobalAllocation.php @@ -66,7 +66,7 @@ } protected function getRequestParams() { - $sanitize = function( $param, $regex ) { + $sanitize = function ( $param, $regex ) { return filter_var( $param, FILTER_VALIDATE_REGEXP, [ 'options' => [ 'regexp' => $regex ] ] ); }; @@ -293,7 +293,7 @@ foreach ( $grouping['rows'] as $row ) { $htmlOut .= Html::openElement( 'tr', - [ 'class'=>'mw-sp-centralnotice-allocationrow' ] ); + [ 'class' =>'mw-sp-centralnotice-allocationrow' ] ); $htmlOut .= Html::openElement( 'td' ); $htmlOut .= $row['projects_label']; @@ -421,7 +421,7 @@ * @throws InvalidArgumentException */ protected static function makeCombinations( array $list, $num ) { - if ( $num <= 0 or $num > count( $list ) ) { + if ( $num <= 0 || $num > count( $list ) ) { throw new InvalidArgumentException( "bad arguments to makeCombinations" ); } if ( $num == count( $list ) ) { @@ -568,7 +568,7 @@ $viewCampaign = $this->getTitleFor( 'CentralNotice' ); // Row begin - $htmlOut .= Html::openElement( 'tr', [ 'class'=>'mw-sp-centralnotice-allocationrow' ] ); + $htmlOut .= Html::openElement( 'tr', [ 'class' =>'mw-sp-centralnotice-allocationrow' ] ); if ( !$variesAnon ) { $anonLabel = $this->msg( 'centralnotice-all' )->text(); @@ -641,21 +641,22 @@ * @param string $project */ protected static function filterCampaigns( - $campaigns, $country, $language, $project ) { + $campaigns, $country, $language, $project + ) { $filtered = []; foreach ( $campaigns as $campaign ) { $projectAllowed = ( !$project - or in_array( $project, $campaign['projects'] ) + || in_array( $project, $campaign['projects'] ) ); $languageAllowed = ( !$language - or in_array( $language, $campaign['languages'] ) + || in_array( $language, $campaign['languages'] ) ); $countryAllowed = ( !$country - or !$campaign['geotargeted'] - or in_array( $country, $campaign['countries'] ) + || !$campaign['geotargeted'] + || in_array( $country, $campaign['countries'] ) ); if ( $projectAllowed && $languageAllowed && $countryAllowed ) { $filtered[] = $campaign; @@ -671,7 +672,7 @@ ]; public static function intersect( $a, $b ) { - if ( !$a or !$b ) { + if ( !$a || !$b ) { return false; } foreach ( self::$criteria as $property ) { diff --git a/special/SpecialHideBanners.php b/special/SpecialHideBanners.php index c0a03af..11739e4 100644 --- a/special/SpecialHideBanners.php +++ b/special/SpecialHideBanners.php @@ -19,9 +19,9 @@ $wgCentralNoticeFallbackHideCookieDuration; // Handle /P3P subpage with explanation of invalid P3P header - if ( ( strval( $par ) === SpecialHideBanners::P3P_SUBPAGE ) && - !$wgCentralNoticeHideBannersP3P ){ - + if ( ( strval( $par ) === self::P3P_SUBPAGE ) && + !$wgCentralNoticeHideBannersP3P + ) { $this->setHeaders(); $this->getOutput()->addWikiMsg( 'centralnotice-specialhidebanners-p3p' ); return; @@ -52,7 +52,7 @@ header( 'Content-Type: image/png' ); if ( !$this->getUser()->isLoggedIn() ) { - $expiry = SpecialHideBanners::CACHE_EXPIRY; + $expiry = self::CACHE_EXPIRY; header( "Cache-Control: public, s-maxage={$expiry}, max-age=0" ); } } @@ -94,9 +94,8 @@ global $wgCentralNoticeHideBannersP3P; if ( !$wgCentralNoticeHideBannersP3P ) { - $url = SpecialPage::getTitleFor( - 'HideBanners', SpecialHideBanners::P3P_SUBPAGE ) + 'HideBanners', self::P3P_SUBPAGE ) ->getCanonicalURL(); $p3p = "CP=\"This is not a P3P policy! See $url for more info.\""; diff --git a/tests/AllocationCalculatorTest.php b/tests/AllocationCalculatorTest.php index 9c2db4b..d3af843 100644 --- a/tests/AllocationCalculatorTest.php +++ b/tests/AllocationCalculatorTest.php @@ -24,7 +24,6 @@ * @dataProvider CentralNoticeTestFixtures::allocationsTestCasesProvision */ public function testAllocations( $name, $testCase ) { - global $wgNoticeNumberOfBuckets; // Set up database with campaigns and banners from fixtures @@ -33,7 +32,6 @@ // Run through the contexts and outputs to calculate and test // allocations for each. foreach ( $testCase['contexts_and_outputs'] as $cAndOName => $cAndO ) { - $fixtureIdMsg = "Test case: {$name}. Context: {$cAndOName}."; // Get choices for this context, then filter and allocate campaigns @@ -66,7 +64,6 @@ ); foreach ( $choices as $campaign ) { - $campaignName = $campaign['name']; // Test that the campaign was expected and was correctly allocated @@ -91,7 +88,6 @@ // Cycle through buckets and allocate banners for each for ( $bucket = 0; $bucket < $wgNoticeNumberOfBuckets; $bucket++ ) { - $expectedBanners = $expectedCampaign['banners'][$bucket]; $banners = AllocationCalculator::makePossibleBanners( @@ -111,7 +107,6 @@ ); foreach ( $banners as $banner ) { - $bannerName = $banner['name']; // Test the banner was expected and was correctly allocated diff --git a/tests/ApiCentralNoticeChoiceDataTest.php b/tests/ApiCentralNoticeChoiceDataTest.php index 33fcb57..1fd3062 100644 --- a/tests/ApiCentralNoticeChoiceDataTest.php +++ b/tests/ApiCentralNoticeChoiceDataTest.php @@ -24,11 +24,9 @@ * @dataProvider CentralNoticeTestFixtures::allocationsTestCasesProvision */ public function testChoiceDataResponse( $name, $testCase ) { - $this->cnFixtures->setupTestCaseFromFixtureData( $testCase ); foreach ( $testCase['contexts_and_outputs'] as $cAndOName => $contextAndOutput ) { - $ret = $this->doApiRequest( [ 'action' => 'centralnoticechoicedata', 'project' => $contextAndOutput['context']['project'], diff --git a/tests/BannerTest.php b/tests/BannerTest.php index ff764f8..2ef3c94 100644 --- a/tests/BannerTest.php +++ b/tests/BannerTest.php @@ -11,7 +11,7 @@ protected $fixture; public static function setUpBeforeClass() { - $banner = Banner::fromName( BannerTest::TEST_BANNER_NAME ); + $banner = Banner::fromName( self::TEST_BANNER_NAME ); if ( $banner->exists() ) { $banner->remove(); } @@ -26,7 +26,7 @@ } public function tearDown() { - $banner = Banner::fromName( BannerTest::TEST_BANNER_NAME ); + $banner = Banner::fromName( self::TEST_BANNER_NAME ); if ( $banner->exists() ) { $banner->remove(); } @@ -35,13 +35,13 @@ public function testNewFromName() { // Create what should be a new empty banner - $banner = Banner::newFromName( BannerTest::TEST_BANNER_NAME ); + $banner = Banner::newFromName( self::TEST_BANNER_NAME ); $this->assertFalse( $banner->exists(), 'Test precondition failed! Banner already exists!' ); // Run down the basic metadata and ensure it is in fact empty $this->assertEquals( null, $banner->getId(), 'New banner ID is not null; probably already exists!' ); - $this->assertEquals( BannerTest::TEST_BANNER_NAME, $banner->getName(), + $this->assertEquals( self::TEST_BANNER_NAME, $banner->getName(), 'Banner name did not get set' ); $this->assertFalse( $banner->allocateToAnon(), 'Initial anonymous allocation is set to true' ); @@ -77,13 +77,13 @@ * @depends testNewFromName */ public function testEmptyFromName() { - $banner = Banner::newFromName( BannerTest::TEST_BANNER_NAME ); + $banner = Banner::newFromName( self::TEST_BANNER_NAME ); $banner->save(); $this->assertTrue( $banner->exists(), 'Test banner that should exist does not!' ); // Run down the basic metadata and ensure it is in fact empty $this->assertNotEquals( -1, $banner->getId(), 'Test banner has no ID' ); - $this->assertEquals( BannerTest::TEST_BANNER_NAME, $banner->getName(), + $this->assertEquals( self::TEST_BANNER_NAME, $banner->getName(), 'Banner name did not get saved' ); $this->assertFalse( $banner->allocateToAnon(), 'Initial anonymous allocation is set to true' ); @@ -110,13 +110,12 @@ * @depends testEmptyFromName */ public function testBasicSave() { - $banner = Banner::newFromName( BannerTest::TEST_BANNER_NAME ); + $banner = Banner::newFromName( self::TEST_BANNER_NAME ); $banner->save(); $this->assertTrue( $banner->exists() ); // Attempt to populate basic metadata - $banner->setAllocation( true, true )-> - setCategory( 'testCategory' ); + $banner->setAllocation( true, true )->setCategory( 'testCategory' ); // And the more advanced metadata $banner->setDevices( 'desktop' ); @@ -138,7 +137,7 @@ "Failed prilang retrieve from initial" ); // Can we retrieve it from a different object - $banner2 = Banner::fromName( BannerTest::TEST_BANNER_NAME ); + $banner2 = Banner::fromName( self::TEST_BANNER_NAME ); $this->assertTrue( $banner2->allocateToAnon(), "Failed anon allocation from copy" ); $this->assertTrue( $banner2->allocateToLoggedIn(), "Failed loggedin allocation from copy" ); $this->assertEquals( 'testCategory', $banner2->getCategory(), "Failed category from copy" ); @@ -158,14 +157,14 @@ * @dataProvider providerSetAllocation */ public function testSetAllocation( $anon, $loggedIn ) { - $banner = Banner::newFromName( BannerTest::TEST_BANNER_NAME ); + $banner = Banner::newFromName( self::TEST_BANNER_NAME ); $banner->setAllocation( $anon, $loggedIn ); $banner->save(); $this->assertEquals( $anon, $banner->allocateToAnon(), "Testing initial anon" ); $this->assertEquals( $loggedIn, $banner->allocateToLoggedIn(), "Testing initial logged in" ); - $banner2 = Banner::fromName( BannerTest::TEST_BANNER_NAME ); + $banner2 = Banner::fromName( self::TEST_BANNER_NAME ); $this->assertEquals( $anon, $banner2->allocateToAnon(), "Testing post save anon" ); $this->assertEquals( $loggedIn, $banner2->allocateToLoggedIn(), "Testing post save logged in" ); diff --git a/tests/CNChoiceDataResourceLoaderModuleTest.php b/tests/CNChoiceDataResourceLoaderModuleTest.php index f41838d..feb846e 100644 --- a/tests/CNChoiceDataResourceLoaderModuleTest.php +++ b/tests/CNChoiceDataResourceLoaderModuleTest.php @@ -32,7 +32,6 @@ $this->cnFixtures->setupTestCaseFromFixtureData( $testCase ); foreach ( $testCase['contexts_and_outputs'] as $cAndOName => $contextAndOutput ) { - $this->setMwGlobals( [ 'wgNoticeProject' => $contextAndOutput['context']['project'], ] ); diff --git a/tests/CentralNoticeTestFixtures.php b/tests/CentralNoticeTestFixtures.php index 2cde252..7fa8f79 100644 --- a/tests/CentralNoticeTestFixtures.php +++ b/tests/CentralNoticeTestFixtures.php @@ -20,11 +20,11 @@ 'enabled' => 1, // inclusive comparison is used, so this does not cause a race condition. 'startTs' => wfTimestamp( TS_MW ), - 'projects' => [ CentralNoticeTestFixtures::getDefaultProject() ], - 'languages' => [ CentralNoticeTestFixtures::getDefaultLanguage() ], + 'projects' => [ self::getDefaultProject() ], + 'languages' => [ self::getDefaultLanguage() ], 'preferred' => CentralNotice::NORMAL_PRIORITY, 'geotargeted' => 0, - 'countries' => [ CentralNoticeTestFixtures::getDefaultCountry() ], + 'countries' => [ self::getDefaultCountry() ], 'throttle' => 100, 'banners' => [], ]; @@ -59,7 +59,7 @@ * as appropriate for fixture data. */ function getGlobalsFromFixtureData() { - $data = CentralNoticeTestFixtures::allocationsData(); + $data = self::allocationsData(); return $data['mock_config_values']; } @@ -100,15 +100,14 @@ * test case specification */ protected function addTestCaseDefaults( &$testCaseSetup ) { - foreach ( $testCaseSetup['campaigns'] as &$campaign ) { $campaign = $campaign + static::$defaultCampaign + [ - 'name' => 'TestCampaign_' . rand(), + 'name' => 'TestCampaign_' . rand(), ]; foreach ( $campaign['banners'] as &$banner ) { $banner = $banner + static::$defaultBanner + [ - 'name' => 'TestBanner_' . rand(), + 'name' => 'TestBanner_' . rand(), ]; } } @@ -124,30 +123,31 @@ * @param array $testCase A data structure with the test case specification */ protected function setTestCaseStartEnd( &$testCase ) { - $now = wfTimestamp(); foreach ( $testCase['setup']['campaigns'] as &$campaign ) { - - $start = CentralNoticeTestFixtures::makeTimestamp( - $now, $campaign['start_days_from_now'] ); + $start = self::makeTimestamp( + $now, $campaign['start_days_from_now'] + ); $campaign['startTs'] = wfTimestamp( TS_MW, $start ); - $end = CentralNoticeTestFixtures::makeTimestamp( - $now, $campaign['end_days_from_now'] ); + $end = self::makeTimestamp( + $now, $campaign['end_days_from_now'] + ); $campaign['endTs'] = wfTimestamp( TS_MW, $end ); } foreach ( $testCase['contexts_and_outputs'] as &$context_and_output ) { foreach ( $context_and_output['choices'] as &$choice ) { + $choice['start'] = self::makeTimestamp( + $now, $choice['start_days_from_now'] + ); - $choice['start'] = CentralNoticeTestFixtures::makeTimestamp( - $now, $choice['start_days_from_now'] ); - - $choice['end'] = CentralNoticeTestFixtures::makeTimestamp( - $now, $choice['end_days_from_now'] ); + $choice['end'] = self::makeTimestamp( + $now, $choice['end_days_from_now'] + ); $choice['mixins'] = []; @@ -169,15 +169,13 @@ * test case specification */ protected function preprocessSetupCountriesProp( &$testCaseSetup ) { - foreach ( $testCaseSetup['campaigns'] as &$campaign ) { - if ( !$campaign['geotargeted'] ) { if ( !isset( $campaign['countries'] ) ) { $campaign['countries'] = []; } else { throw new LogicException( "Campaign is not geotargetted but " - . "'countries' property is set." ); + . "'countries' property is set." ); } } } @@ -216,7 +214,6 @@ * test case specification */ protected function setupTestCase( $testCaseSetup ) { - // It is expected that when a test case is set up via fixture data, // this global will already have been set via // setupTestCaseFromFixtureData(). Legacy (non-fixture data) tests don't @@ -227,7 +224,6 @@ $this->ensureDesktopDevice(); foreach ( $testCaseSetup['campaigns'] as $campaign ) { - $campaign['id'] = Campaign::addCampaign( $campaign['name'], $campaign['enabled'], @@ -252,12 +248,12 @@ // bucket_count and archived are also only in test // fixture data, not legacy tests. if ( isset( $campaign['bucket_count'] ) ) { - $bucket_count = $campaign['bucket_count']; if ( $bucket_count < 1 || - $bucket_count > $wgNoticeNumberOfBuckets ) { - throw new RangeException( 'Bucket count out of range.' ); + $bucket_count > $wgNoticeNumberOfBuckets + ) { + throw new RangeException( 'Bucket count out of range.' ); } Campaign::setNumericCampaignSetting( @@ -304,7 +300,8 @@ Campaign::updateBucket( $campaign['name'], $bannerObj->getId(), - $bannerSpec['bucket'] ); + $bannerSpec['bucket'] + ); } if ( isset( $bannerSpec['devices'] ) ) { @@ -350,9 +347,8 @@ * @param array $actual Actual choices data structure */ function assertChoicesEqual( MediaWikiTestCase $testClass, $expected, $actual, - $message='' + $message = '' ) { - // The order of the numerically indexed arrays in this data structure // shouldn't matter, so sort all of those by value. $this->deepMultisort( $expected ); @@ -401,7 +397,6 @@ // Add any devices not in the database foreach ( $deviceNames as $deviceName ) { if ( !isset( $this->knownDevices[$deviceName] ) ) { - // Remember the IDs for teardown $this->addedDeviceIds[] = CNDeviceTarget::addDeviceTarget( $deviceName, $deviceName ); @@ -423,7 +418,7 @@ * a test method.) */ public static function allocationsTestCasesProvision() { - $data = CentralNoticeTestFixtures::allocationsData(); + $data = self::allocationsData(); $dataForTests = []; foreach ( $data['test_cases'] as $name => $testCase ) { @@ -438,7 +433,7 @@ * scenario for testing. */ public static function allocationsData() { - $json = CentralNoticeTestFixtures::allocationsDataAsJson(); + $json = self::allocationsDataAsJson(); $data = FormatJson::decode( $json, true ); return $data; } @@ -448,7 +443,7 @@ * CentralNoticeTestFixtures::FIXTURE_RELATIVE_PATH). */ public static function allocationsDataAsJson() { - $path = __DIR__ . '/' . CentralNoticeTestFixtures::FIXTURE_RELATIVE_PATH; + $path = __DIR__ . '/' . self::FIXTURE_RELATIVE_PATH; return file_get_contents( $path ); } } diff --git a/tests/ChoiceDataProviderTest.php b/tests/ChoiceDataProviderTest.php index e6f55ac..737497c 100644 --- a/tests/ChoiceDataProviderTest.php +++ b/tests/ChoiceDataProviderTest.php @@ -24,11 +24,9 @@ * @dataProvider CentralNoticeTestFixtures::allocationsTestCasesProvision */ public function testProviderResponse( $name, $testCase ) { - $this->cnFixtures->setupTestCaseFromFixtureData( $testCase ); foreach ( $testCase['contexts_and_outputs'] as $cANdOName => $contextAndOutput ) { - $choices = ChoiceDataProvider::getChoices( $contextAndOutput['context']['project'], $contextAndOutput['context']['language'] -- To view, visit https://gerrit.wikimedia.org/r/364039 To unsubscribe, visit https://gerrit.wikimedia.org/r/settings Gerrit-MessageType: merged Gerrit-Change-Id: I5f9d1c386ffe6ecf6c483c67471a9f14080c7c77 Gerrit-PatchSet: 6 Gerrit-Project: mediawiki/extensions/CentralNotice Gerrit-Branch: master Gerrit-Owner: Umherirrender <umherirrender_de...@web.de> Gerrit-Reviewer: AndyRussG <andrew.green...@gmail.com> Gerrit-Reviewer: Cdentinger <cdentin...@wikimedia.org> Gerrit-Reviewer: Ejegg <ej...@ejegg.com> Gerrit-Reviewer: Jforrester <jforres...@wikimedia.org> Gerrit-Reviewer: Legoktm <lego...@member.fsf.org> Gerrit-Reviewer: Reedy <re...@wikimedia.org> Gerrit-Reviewer: Thiemo Mättig (WMDE) <thiemo.maet...@wikimedia.de> Gerrit-Reviewer: Umherirrender <umherirrender_de...@web.de> Gerrit-Reviewer: XenoRyet <dkozlow...@wikimedia.org> Gerrit-Reviewer: jenkins-bot <> _______________________________________________ MediaWiki-commits mailing list MediaWiki-commits@lists.wikimedia.org https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits