Completed
Push — master ( 3eff13...afdb92 )
by
unknown
03:28 queued 13s
created

onWikibaseChange()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 29

Duplication

Lines 18
Ratio 62.07 %

Importance

Changes 0
Metric Value
dl 18
loc 29
rs 8.5226
c 0
b 0
f 0
cc 7
nc 5
nop 1
1
<?php
2
3
namespace WikibaseQuality\ConstraintReport;
4
5
use BetaFeatures;
6
use Config;
7
use DatabaseUpdater;
8
use ExtensionRegistry;
9
use JobQueueGroup;
10
use JobSpecification;
11
use MediaWiki\MediaWikiServices;
12
use OutputPage;
13
use Skin;
14
use User;
15
use Wikibase\Change;
16
use Wikibase\DataModel\Entity\PropertyId;
17
use Wikibase\EntityChange;
18
use Wikibase\Lib\Changes\EntityDiffChangedAspects;
19
use Wikibase\Repo\WikibaseRepo;
20
use WikibaseQuality\ConstraintReport\Api\ResultsCache;
21
use WikibaseQuality\ConstraintReport\Job\CheckConstraintsJob;
22
use WikiPage;
23
24
/**
25
 * Container for hook callbacks registered in extension.json.
26
 *
27
 * @license GPL-2.0-or-later
28
 */
29
final class WikibaseQualityConstraintsHooks {
30
31
	/**
32
	 * @param DatabaseUpdater $updater
33
	 */
34
	public static function onCreateSchema( DatabaseUpdater $updater ) {
35
		$updater->addExtensionTable(
36
			'wbqc_constraints',
37
			__DIR__ . '/../sql/create_wbqc_constraints.sql'
38
		);
39
		$updater->addExtensionField(
40
			'wbqc_constraints',
41
			'constraint_id',
42
			__DIR__ . '/../sql/patch-wbqc_constraints-constraint_id.sql'
43
		);
44
		$updater->addExtensionIndex(
45
			'wbqc_constraints',
46
			'wbqc_constraints_guid_uniq',
47
			__DIR__ . '/../sql/patch-wbqc_constraints-wbqc_constraints_guid_uniq.sql'
48
		);
49
	}
50
51
	public static function onWikibaseChange( Change $change ) {
52
		if ( !( $change instanceof EntityChange ) ) {
0 ignored issues
show
Bug introduced by
The class Wikibase\EntityChange does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
53
			return;
54
		}
55
56
		/** @var EntityChange $change */
57
		$config = MediaWikiServices::getInstance()->getMainConfig();
58
59
		// If jobs are enabled and the results would be stored in some way run a job.
60 View Code Duplication
		if (
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
61
			$config->get( 'WBQualityConstraintsEnableConstraintsCheckJobs' ) &&
62
			$config->get( 'WBQualityConstraintsCacheCheckConstraintsResults' ) &&
63
			self::isSelectedForJobRunBasedOnPercentage()
64
		) {
65
			$params = [ 'entityId' => $change->getEntityId()->getSerialization() ];
66
			JobQueueGroup::singleton()->push(
67
				new JobSpecification( CheckConstraintsJob::COMMAND, $params )
68
			);
69
		}
70
71 View Code Duplication
		if ( $config->get( 'WBQualityConstraintsEnableConstraintsImportFromStatements' ) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
72
			self::isConstraintStatementsChange( $config, $change )
73
		) {
74
			$params = [ 'propertyId' => $change->getEntityId()->getSerialization() ];
75
			JobQueueGroup::singleton()->push(
76
				new JobSpecification( 'constraintsTableUpdate', $params )
77
			);
78
		}
79
	}
80
81
	private static function isSelectedForJobRunBasedOnPercentage() {
82
		$config = MediaWikiServices::getInstance()->getMainConfig();
83
		$percentage = $config->get( 'WBQualityConstraintsEnableConstraintsCheckJobsRatio' );
84
85
		return mt_rand( 1, 100 ) <= $percentage;
86
	}
87
88
	public static function isConstraintStatementsChange( Config $config, Change $change ) {
89
		if ( !( $change instanceof EntityChange ) ||
0 ignored issues
show
Bug introduced by
The class Wikibase\EntityChange does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
90
			 $change->getAction() !== EntityChange::UPDATE ||
91
			 !( $change->getEntityId() instanceof PropertyId )
92
		) {
93
			return false;
94
		}
95
96
		$info = $change->getInfo();
97
98
		if ( !array_key_exists( 'compactDiff', $info ) ) {
99
			// the non-compact diff ($info['diff']) does not contain statement diffs (T110996),
100
			// so we only know that the change *might* affect the constraint statements
101
			return true;
102
		}
103
104
		/** @var EntityDiffChangedAspects $aspects */
105
		$aspects = $info['compactDiff'];
106
107
		$propertyConstraintId = $config->get( 'WBQualityConstraintsPropertyConstraintId' );
108
		return in_array( $propertyConstraintId, $aspects->getStatementChanges() );
109
	}
110
111
	public static function onArticlePurge( WikiPage $wikiPage ) {
112
		$repo = WikibaseRepo::getDefaultInstance();
113
114
		$entityContentFactory = $repo->getEntityContentFactory();
115
		if ( $entityContentFactory->isEntityContentModel( $wikiPage->getContentModel() ) ) {
116
			$entityId = $entityContentFactory->getEntityIdForTitle( $wikiPage->getTitle() );
117
			if ( $entityId !== null ) {
118
				$resultsCache = ResultsCache::getDefaultInstance();
119
				$resultsCache->delete( $entityId );
120
			}
121
		}
122
	}
123
124
	public static function onBeforePageDisplay( OutputPage $out, Skin $skin ) {
0 ignored issues
show
Unused Code introduced by
The parameter $skin is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
125
		$repo = WikibaseRepo::getDefaultInstance();
126
127
		$lookup = $repo->getEntityNamespaceLookup();
128
		$title = $out->getTitle();
129
		if ( $title === null ) {
130
			return;
131
		}
132
133
		if ( !$lookup->isEntityNamespace( $title->getNamespace() ) ) {
134
			return;
135
		}
136
		if ( empty( $out->getJsConfigVars()['wbIsEditView'] ) ) {
137
			return;
138
		}
139
140
		$out->addModules( 'wikibase.quality.constraints.suggestions' );
141
142
		if ( !$out->getUser()->isLoggedIn() ) {
143
			return;
144
		}
145
146
		$out->addModules( 'wikibase.quality.constraints.gadget' );
147
	}
148
149
	/**
150
	 * @see https://www.mediawiki.org/wiki/Manual:Hooks/GetBetaFeaturePreferences
151
	 *
152
	 * @param User $user
153
	 * @param array[] &$prefs
154
	 */
155
	public static function onGetBetaFeaturePreferences( User $user, array &$prefs ) {
0 ignored issues
show
Unused Code introduced by
The parameter $user is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
156
		$config = MediaWikiServices::getInstance()->getMainConfig();
157
		$extensionAssetsPath = $config->get( 'ExtensionAssetsPath' );
158
		if ( $config->get( 'WBQualityConstraintsSuggestionsBetaFeature' ) ) {
159
			$prefs['constraint-suggestions'] = [
160
					'label-message' => 'wbqc-beta-feature-label-message',
161
					'desc-message' => 'wbqc-beta-feature-description-message',
162
					'screenshot' => [
163
							'ltr' => "$extensionAssetsPath/WikibaseQualityConstraints/resources/ConstraintSuggestions-beta-features-ltr.svg",
164
							'rtl' => "$extensionAssetsPath/WikibaseQualityConstraints/resources/ConstraintSuggestions-beta-features-rtl.svg",
165
					],
166
					'info-link'
167
					=> 'https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Constraints_suggestions',
168
					'discussion-link'
169
					=> 'https://www.mediawiki.org/wiki/Help_talk:Constraints_suggestions',
170
					'requirements' => [
171
							'javascript' => true,
172
					],
173
			];
174
		}
175
	}
176
177
	/**
178
	 * Hook: MakeGlobalVariablesScript
179
	 * @param array &$vars
180
	 * @param OutputPage $out
181
	 */
182
	public static function addVariables( &$vars, OutputPage $out ) {
183
		$config = MediaWikiServices::getInstance()->getMainConfig();
184
185
		$vars['wbQualityConstraintsPropertyConstraintId'] = $config->get( 'WBQualityConstraintsPropertyConstraintId' );
186
		$vars['wbQualityConstraintsOneOfConstraintId'] = $config->get( 'WBQualityConstraintsOneOfConstraintId' );
187
		$vars['wbQualityConstraintsAllowedQualifierConstraintId'] = $config->get( 'WBQualityConstraintsAllowedQualifiersConstraintId' );
188
		$vars['wbQualityConstraintsPropertyId'] = $config->get( 'WBQualityConstraintsPropertyId' );
189
		$vars['wbQualityConstraintsQualifierOfPropertyConstraintId'] = $config->get( 'WBQualityConstraintsQualifierOfPropertyConstraintId' );
190
191
		$vars['wbQualityConstraintsSuggestionsGloballyEnabled'] = false;
192
193
		if ( $config->get( 'WBQualityConstraintsSuggestionsBetaFeature' ) &&
194
			ExtensionRegistry::getInstance()->isLoaded( 'BetaFeatures' ) &&
195
			BetaFeatures::isFeatureEnabled( $out->getUser(), 'constraint-suggestions' )
196
			) {
197
			$vars['wbQualityConstraintsSuggestionsGloballyEnabled'] = true;
198
		}
199
	}
200
201
}
202