RemoveClaims   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 245
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
wmc 20
lcom 1
cbo 11
dl 0
loc 245
rs 10
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 22 1
A factory() 0 28 1
A execute() 0 28 3
B getEntityId() 0 23 6
A assertStatementListContainsGuids() 0 20 3
A getChangeOps() 0 9 2
A isWriteMode() 0 3 1
A needsToken() 0 3 1
A getAllowedParams() 0 24 1
A getExamplesMessages() 0 7 1
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace Wikibase\Repo\Api;
6
7
use ApiBase;
8
use ApiMain;
9
use Wikibase\DataModel\Entity\EntityId;
10
use Wikibase\DataModel\Services\Statement\StatementGuidParser;
11
use Wikibase\DataModel\Statement\Statement;
12
use Wikibase\DataModel\Statement\StatementList;
13
use Wikibase\DataModel\Statement\StatementListProvider;
14
use Wikibase\Repo\ChangeOp\ChangeOp;
15
use Wikibase\Repo\ChangeOp\ChangeOpException;
16
use Wikibase\Repo\ChangeOp\ChangeOps;
17
use Wikibase\Repo\ChangeOp\StatementChangeOpFactory;
18
use Wikibase\Repo\WikibaseRepo;
19
20
/**
21
 * API module for removing claims.
22
 *
23
 * @license GPL-2.0-or-later
24
 * @author Jeroen De Dauw < [email protected] >
25
 * @author Tobias Gritschacher < [email protected] >
26
 */
27
class RemoveClaims extends ApiBase {
28
29
	use FederatedPropertyApiValidatorTrait;
30
31
	/**
32
	 * @var StatementChangeOpFactory
33
	 */
34
	private $statementChangeOpFactory;
35
36
	/**
37
	 * @var ApiErrorReporter
38
	 */
39
	protected $errorReporter;
40
41
	/**
42
	 * @var StatementModificationHelper
43
	 */
44
	private $modificationHelper;
45
46
	/**
47
	 * @var StatementGuidParser
48
	 */
49
	private $guidParser;
50
51
	/**
52
	 * @var ResultBuilder
53
	 */
54
	private $resultBuilder;
55
56
	/**
57
	 * @var EntitySavingHelper
58
	 */
59
	private $entitySavingHelper;
60
61
	public function __construct(
62
		ApiMain $mainModule,
63
		string $moduleName,
64
		ApiErrorReporter $errorReporter,
65
		StatementChangeOpFactory $statementChangeOpFactory,
66
		StatementModificationHelper $modificationHelper,
67
		StatementGuidParser $guidParser,
68
		callable $resultBuilderInstantiator,
69
		callable $entitySavingHelperInstantiator,
70
		bool $federatedPropertiesEnabled
71
	) {
72
		parent::__construct( $mainModule, $moduleName );
73
74
		$this->errorReporter = $errorReporter;
75
		$this->statementChangeOpFactory = $statementChangeOpFactory;
76
		$this->modificationHelper = $modificationHelper;
77
78
		$this->guidParser = $guidParser;
79
		$this->resultBuilder = $resultBuilderInstantiator( $this );
80
		$this->entitySavingHelper = $entitySavingHelperInstantiator( $this );
81
		$this->federatedPropertiesEnabled = $federatedPropertiesEnabled;
82
	}
83
84
	public static function factory( ApiMain $mainModule, string $moduleName ): self {
85
		$wikibaseRepo = WikibaseRepo::getDefaultInstance();
86
		$apiHelperFactory = $wikibaseRepo->getApiHelperFactory( $mainModule->getContext() );
87
		$changeOpFactoryProvider = $wikibaseRepo->getChangeOpFactoryProvider();
88
89
		$modificationHelper = new StatementModificationHelper(
90
			$wikibaseRepo->getSnakFactory(),
91
			$wikibaseRepo->getEntityIdParser(),
92
			$wikibaseRepo->getStatementGuidValidator(),
93
			$apiHelperFactory->getErrorReporter( $mainModule )
94
		);
95
96
		return new self(
97
			$mainModule,
98
			$moduleName,
99
			$apiHelperFactory->getErrorReporter( $mainModule ),
100
			$changeOpFactoryProvider->getStatementChangeOpFactory(),
101
			$modificationHelper,
102
			$wikibaseRepo->getStatementGuidParser(),
103
			function ( $module ) use ( $apiHelperFactory ) {
104
				return $apiHelperFactory->getResultBuilder( $module );
105
			},
106
			function ( $module ) use ( $apiHelperFactory ) {
107
				return $apiHelperFactory->getEntitySavingHelper( $module );
108
			},
109
			$wikibaseRepo->inFederatedPropertyMode()
110
		);
111
	}
112
113
	/**
114
	 * @inheritDoc
115
	 */
116
	public function execute(): void {
117
		$params = $this->extractRequestParams();
118
		$entityId = $this->getEntityId( $params );
119
120
		$this->validateAlteringEntityById( $entityId );
121
122
		$entity = $this->entitySavingHelper->loadEntity( $entityId );
123
124
		if ( $entity instanceof StatementListProvider ) {
125
			$this->assertStatementListContainsGuids( $entity->getStatements(), $params['claim'] );
126
		}
127
128
		$summary = $this->modificationHelper->createSummary( $params, $this );
129
130
		$changeOps = new ChangeOps();
131
		$changeOps->add( $this->getChangeOps( $params ) );
132
133
		try {
134
			$changeOps->apply( $entity, $summary );
135
		} catch ( ChangeOpException $e ) {
136
			$this->errorReporter->dieException( $e, 'failed-save' );
137
		}
138
139
		$status = $this->entitySavingHelper->attemptSaveEntity( $entity, $summary );
140
		$this->resultBuilder->addRevisionIdFromStatusToResult( $status, 'pageinfo' );
141
		$this->resultBuilder->markSuccess();
142
		$this->resultBuilder->setList( null, 'claims', $params['claim'], 'claim' );
143
	}
144
145
	/**
146
	 * Validates the parameters and returns the EntityId to act upon on success
147
	 *
148
	 * @param array $params
149
	 *
150
	 * @return EntityId
151
	 */
152
	private function getEntityId( array $params ): EntityId {
153
		$entityId = null;
154
155
		foreach ( $params['claim'] as $guid ) {
156
			if ( !$this->modificationHelper->validateStatementGuid( $guid ) ) {
157
				$this->errorReporter->dieError( "Invalid claim guid $guid", 'invalid-guid' );
0 ignored issues
show
Deprecated Code introduced by
The method Wikibase\Repo\Api\ApiErrorReporter::dieError() has been deprecated with message: Use dieWithError() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
158
			}
159
160
			if ( $entityId === null ) {
161
				$entityId = $this->guidParser->parse( $guid )->getEntityId();
162
			} else {
163
				if ( !$this->guidParser->parse( $guid )->getEntityId()->equals( $entityId ) ) {
164
					$this->errorReporter->dieError( 'All claims must belong to the same entity', 'invalid-guid' );
0 ignored issues
show
Deprecated Code introduced by
The method Wikibase\Repo\Api\ApiErrorReporter::dieError() has been deprecated with message: Use dieWithError() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
165
				}
166
			}
167
		}
168
169
		if ( $entityId === null ) {
170
			$this->errorReporter->dieError( 'Could not find an entity for the claims', 'invalid-guid' );
0 ignored issues
show
Deprecated Code introduced by
The method Wikibase\Repo\Api\ApiErrorReporter::dieError() has been deprecated with message: Use dieWithError() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
171
		}
172
173
		return $entityId;
174
	}
175
176
	/**
177
	 * @param StatementList $statements
178
	 * @param string[] $requiredGuids
179
	 */
180
	private function assertStatementListContainsGuids( StatementList $statements, array $requiredGuids ): void {
181
		$existingGuids = [];
182
183
		/** @var Statement $statement */
184
		foreach ( $statements as $statement ) {
185
			$guid = $statement->getGuid();
186
			// This array is used as a HashSet where only the keys are used.
187
			$existingGuids[$guid] = null;
188
		}
189
190
		// Not using array_diff but array_diff_key does have a huge performance impact.
191
		$missingGuids = array_diff_key( array_flip( $requiredGuids ), $existingGuids );
192
193
		if ( !empty( $missingGuids ) ) {
194
			$this->errorReporter->dieError(
0 ignored issues
show
Deprecated Code introduced by
The method Wikibase\Repo\Api\ApiErrorReporter::dieError() has been deprecated with message: Use dieWithError() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
195
				'Statement(s) with GUID(s) ' . implode( ', ', array_keys( $missingGuids ) ) . ' not found',
196
				'invalid-guid'
197
			);
198
		}
199
	}
200
201
	/**
202
	 * @param array $params
203
	 *
204
	 * @return ChangeOp[]
205
	 */
206
	private function getChangeOps( array $params ): array {
207
		$changeOps = [];
208
209
		foreach ( $params['claim'] as $guid ) {
210
			$changeOps[] = $this->statementChangeOpFactory->newRemoveStatementOp( $guid );
211
		}
212
213
		return $changeOps;
214
	}
215
216
	/**
217
	 * @inheritDoc
218
	 */
219
	public function isWriteMode(): bool {
220
		return true;
221
	}
222
223
	/**
224
	 * @see ApiBase::needsToken
225
	 *
226
	 * @return string
227
	 */
228
	public function needsToken(): string {
229
		return 'csrf';
230
	}
231
232
	/**
233
	 * @inheritDoc
234
	 */
235
	protected function getAllowedParams(): array {
236
		return array_merge(
237
			[
238
				'claim' => [
239
					self::PARAM_TYPE => 'string',
240
					self::PARAM_ISMULTI => true,
241
					self::PARAM_REQUIRED => true,
242
				],
243
				'summary' => [
244
					self::PARAM_TYPE => 'string',
245
				],
246
				'tags' => [
247
					self::PARAM_TYPE => 'tags',
248
					self::PARAM_ISMULTI => true,
249
				],
250
				'token' => null,
251
				'baserevid' => [
252
					self::PARAM_TYPE => 'integer',
253
				],
254
				'bot' => false,
255
			],
256
			parent::getAllowedParams()
257
		);
258
	}
259
260
	/**
261
	 * @inheritDoc
262
	 */
263
	protected function getExamplesMessages(): array {
264
		return [
265
			'action=wbremoveclaims&claim=Q42$D8404CDA-25E4-4334-AF13-A3290BCD9C0N&token=foobar'
266
				. '&baserevid=7201010'
267
				=> 'apihelp-wbremoveclaims-example-1',
268
		];
269
	}
270
271
}
272