Completed
Push — main ( b55b92...e8d442 )
by
unknown
05:41
created

StatementCreator::create()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 8.9137
c 0
b 0
f 0
cc 6
nc 7
nop 3
1
<?php
2
3
namespace Addwiki\Wikibase\Api\Service;
4
5
use Addwiki\Mediawiki\DataModel\EditInfo;
6
use Addwiki\Wikibase\Api\WikibaseApi;
7
use Serializers\Serializer;
8
use UnexpectedValueException;
9
use Wikibase\DataModel\Entity\EntityId;
10
use Wikibase\DataModel\Entity\Item;
11
use Wikibase\DataModel\Entity\Property;
12
use Wikibase\DataModel\Snak\PropertyValueSnak;
13
use Wikibase\DataModel\Snak\Snak;
14
15
/**
16
 * @access private
17
 *
18
 * @author Addshore
19
 */
20
class StatementCreator {
21
22
	private WikibaseApi $api;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_STRING, expecting T_FUNCTION or T_CONST
Loading history...
23
24
	private \Serializers\Serializer $dataValueSerializer;
25
26
	/**
27
	 * @param WikibaseApi $api
28
	 * @param Serializer $dataValueSerializer
29
	 */
30
	public function __construct( WikibaseApi $api, Serializer $dataValueSerializer ) {
31
		$this->api = $api;
32
		$this->dataValueSerializer = $dataValueSerializer;
33
	}
34
35
	/**
36
	 * @since 0.2
37
	 *
38
	 * @param Snak $mainSnak
39
	 * @param EntityId|Item|Property|string $target
40
	 * @param EditInfo|null $editInfo
41
	 *
42
	 * @return string the GUID of the claim
43
	 * @throws UnexpectedValueException
44
	 */
45
	public function create( Snak $mainSnak, $target, EditInfo $editInfo = null ): string {
46
		if ( is_string( $target ) ) {
47
			$entityId = $target;
48
		} elseif ( $target instanceof EntityId ) {
49
			$entityId = $target->getSerialization();
50
		} elseif ( $target instanceof Item || $target instanceof Property ) {
51
			$entityId = $target->getId()->getSerialization();
52
		} else {
53
			throw new UnexpectedValueException( '$target needs to be an EntityId, Entity or string' );
54
		}
55
56
		$params = [
57
			'entity' => $entityId,
58
			'snaktype' => $mainSnak->getType(),
59
			'property' => $mainSnak->getPropertyId()->getSerialization(),
60
		];
61
		if ( $mainSnak instanceof PropertyValueSnak ) {
62
			$serializedDataValue = $this->dataValueSerializer->serialize( $mainSnak->getDataValue() );
63
			$params['value'] = json_encode( $serializedDataValue['value'] );
64
		}
65
66
		$result = $this->api->postRequest( 'wbcreateclaim', $params, $editInfo );
67
		return $result['claim']['id'];
68
	}
69
70
}
71