UpdateRepoJob::getItem()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 32
rs 9.408
c 0
b 0
f 0
cc 3
nc 3
nop 0
1
<?php
2
3
namespace Wikibase\Repo\UpdateRepo;
4
5
use Job;
6
use Psr\Log\LoggerInterface;
7
use User;
8
use Wikibase\DataModel\Entity\Item;
9
use Wikibase\DataModel\Entity\ItemId;
10
use Wikibase\DataModel\Services\Lookup\EntityLookup;
11
use Wikibase\DataModel\Services\Lookup\EntityLookupException;
12
use Wikibase\Lib\FormatableSummary;
13
use Wikibase\Lib\Store\EntityStore;
14
use Wikibase\Repo\EditEntity\MediawikiEditEntityFactory;
15
use Wikibase\Repo\SummaryFormatter;
16
17
/**
18
 * Job template for updating the repo after a change in client.
19
 *
20
 * @license GPL-2.0-or-later
21
 * @author Marius Hoch < [email protected] >
22
 */
23
abstract class UpdateRepoJob extends Job {
24
25
	/**
26
	 * @var EntityLookup
27
	 */
28
	protected $entityLookup;
29
30
	/**
31
	 * @var EntityStore
32
	 */
33
	protected $entityStore;
34
35
	/**
36
	 * @var SummaryFormatter
37
	 */
38
	protected $summaryFormatter;
39
40
	/**
41
	 * @var LoggerInterface
42
	 */
43
	protected $logger;
44
45
	/**
46
	 * @var MediawikiEditEntityFactory
47
	 */
48
	private $editEntityFactory;
49
50
	protected function initRepoJobServices(
51
		EntityLookup $entityLookup,
52
		EntityStore $entityStore,
53
		SummaryFormatter $summaryFormatter,
54
		LoggerInterface $logger,
55
		MediawikiEditEntityFactory $editEntityFactory
56
	) {
57
		$this->entityLookup = $entityLookup;
58
		$this->entityStore = $entityStore;
59
		$this->summaryFormatter = $summaryFormatter;
60
		$this->logger = $logger;
61
		$this->editEntityFactory = $editEntityFactory;
62
	}
63
64
	/**
65
	 * Initialize repo services from global state.
66
	 */
67
	abstract protected function initRepoJobServicesFromGlobalState();
68
69
	/**
70
	 * Get a Summary object for the edit
71
	 *
72
	 * @return FormatableSummary
73
	 */
74
	abstract public function getSummary();
75
76
	/**
77
	 * Whether the propagated update is valid (and thus should be applied)
78
	 *
79
	 * @param Item $item
80
	 *
81
	 * @return bool
82
	 */
83
	abstract protected function verifyValid( Item $item );
84
85
	/**
86
	 * Apply the changes needed to the given Item.
87
	 *
88
	 * @param Item $item
89
	 *
90
	 * @return bool
91
	 */
92
	abstract protected function applyChanges( Item $item );
93
94
	/**
95
	 * @return Item|null
96
	 */
97
	private function getItem() {
98
		$params = $this->getParams();
99
		$itemId = new ItemId( $params['entityId'] );
100
		try {
101
			$entity = $this->entityLookup->getEntity( $itemId );
102
		} catch ( EntityLookupException $ex ) {
103
			$this->logger->debug(
104
				'{method}: EntityRevision couldn\'t be loaded for {itemIdSerialization}: {msg}',
105
				[
106
					'method' => __METHOD__,
107
					'itemIdSerialization' => $itemId->getSerialization(),
108
					'msg' => $ex->getMessage(),
109
				]
110
			);
111
112
			return null;
113
		}
114
115
		if ( $entity instanceof Item ) {
116
			return $entity;
117
		}
118
119
		$this->logger->debug(
120
			'{method}: EntityRevision not found for {itemIdSerialization}',
121
			[
122
				'method' => __METHOD__,
123
				'itemIdSerialization' => $itemId->getSerialization(),
124
			]
125
		);
126
127
		return null;
128
	}
129
130
	/**
131
	 * Save the new version of the given item.
132
	 *
133
	 * @param Item $item
134
	 * @param User $user
135
	 *
136
	 * @return bool
137
	 */
138
	private function saveChanges( Item $item, User $user ) {
139
		$summary = $this->getSummary();
140
		$itemId = $item->getId();
141
142
		$summaryString = $this->summaryFormatter->formatSummary( $summary );
143
144
		$editEntity = $this->editEntityFactory->newEditEntity( $user, $item->getId(), 0, true );
145
		$status = $editEntity->attemptSave(
146
			$item,
147
			$summaryString,
148
			EDIT_UPDATE,
149
			false,
150
			// Don't (un)watch any pages here, as the user didn't explicitly kick this off
151
			$this->entityStore->isWatching( $user, $itemId )
0 ignored issues
show
Bug introduced by
It seems like $itemId defined by $item->getId() on line 140 can be null; however, Wikibase\Lib\Store\EntityStore::isWatching() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
152
		);
153
154
		if ( !$status->isOK() ) {
155
			$this->logger->debug(
156
				'{method}: attemptSave for {itemIdSerialization} failed: {msgText}',
157
				[
158
					'method' => __METHOD__,
159
					'itemIdSerialization' => $itemId->getSerialization(),
160
					'msgText' => $status->getMessage()->text(),
161
				]
162
			);
163
		}
164
165
		return $status->isOK();
166
	}
167
168
	/**
169
	 * @param string $name
170
	 *
171
	 * @return User|bool
172
	 */
173
	private function getUser( $name ) {
174
		$user = User::newFromName( $name );
175
		if ( !$user || !$user->isLoggedIn() ) {
176
			$this->logger->debug( 'User {name} doesn\'t exist.', [ 'name' => $name ] );
177
			return false;
178
		}
179
180
		return $user;
181
	}
182
183
	/**
184
	 * @return bool success
185
	 */
186
	public function run() {
187
		$params = $this->getParams();
188
189
		$user = $this->getUser( $params['user'] );
190
		if ( !$user ) {
191
			return true;
192
		}
193
194
		$item = $this->getItem();
195
		if ( $item && $this->verifyValid( $item ) ) {
196
			$this->applyChanges( $item );
197
			$this->saveChanges( $item, $user );
198
		}
199
200
		return true;
201
	}
202
203
}
204