Passed
Push — master ( aeb35e...5f0582 )
by Sam
04:41
created
src/Item.php 2 patches
Indentation   +429 added lines, -429 removed lines patch added patch discarded remove patch
@@ -13,158 +13,158 @@  discard block
 block discarded – undo
13 13
 
14 14
 class Item {
15 15
 
16
-	const PROP_INSTANCE_OF = 'P31';
17
-	const PROP_TITLE = 'P1476';
18
-	const PROP_IMAGE = 'P18';
19
-	const PROP_AUTHOR = 'P50';
20
-
21
-	/** @var string */
22
-	protected $id;
23
-
24
-	/** @var MediawikiApi */
25
-	protected $wdApi;
26
-
27
-	/** @var string */
28
-	protected $lang;
29
-
30
-	/** @var CacheItemPoolInterface */
31
-	protected $cache;
32
-
33
-	/** @var string The base URL of Wikidata, with trailing slash. */
34
-	protected $wikidataUrlBase = 'https://www.wikidata.org/wiki/';
35
-
36
-	private function __construct( $id, $lang, CacheItemPoolInterface $cache ) {
37
-		if ( !is_string( $id ) || preg_match( '/[QP][0-9]*/i', $id ) !== 1 ) {
38
-			throw new Exception( "Not a valid ID: " . var_export( $id, true ) );
39
-		}
40
-		$this->id = $id;
41
-		$this->wdApi = new MediawikiApi( 'https://www.wikidata.org/w/api.php' );
42
-		$this->entities = [];
43
-		$this->lang = $lang;
44
-		$this->cache = $cache;
45
-	}
46
-
47
-	/**
48
-	 * Create a new Item object with class based on the item's 'instance of' statement.
49
-	 *
50
-	 * @param string $id The item ID (Q-number).
51
-	 * @param string $lang The language code.
52
-	 * @param CacheItemPoolInterface $cache The cache to use.
53
-	 * @return Item
54
-	 */
55
-	public static function factory( $id, $lang, CacheItemPoolInterface $cache ) {
56
-		$item = new Item( $id, $lang, $cache );
57
-		foreach ( $item->getPropertyOfTypeItem( self::PROP_INSTANCE_OF ) as $instanceOf ) {
58
-			// Try to find a class mating the 'instance of' name.
59
-			$possibleBaseClassName = Str::toCamelCase( $instanceOf->getItem()->getLabel() );
60
-			$possibleClassName = __NAMESPACE__ . '\\Items\\' . $possibleBaseClassName;
61
-			if ( class_exists( $possibleClassName ) ) {
62
-				// This won't re-request the metadata, because that's cached.
63
-				$specificItem = new $possibleClassName( $id, $lang, $cache );
64
-				return $specificItem;
65
-			}
66
-		}
67
-
68
-		// If we're here, just leave it as a basic Item.
69
-		$item->setCache( $cache );
70
-		return $item;
71
-	}
72
-
73
-	/**
74
-	 * @param CacheItemPoolInterface $cache The cache to use.
75
-	 */
76
-	public function setCache( CacheItemPoolInterface $cache ) {
77
-		$this->cache = $cache;
78
-	}
79
-
80
-	/**
81
-	 * Get the ID (Q-number) of this item.
82
-	 * @return string|bool The ID or false if it couldn't be determined.
83
-	 */
84
-	public function getId() {
85
-		$entity = $this->getEntity( $this->id );
86
-		return isset( $entity['id'] ) ? $entity['id'] : false;
87
-	}
88
-
89
-	/**
90
-	 * Get this item's label.
91
-	 * @return string
92
-	 */
93
-	public function getLabel() {
94
-		$entity = $this->getEntity( $this->id );
95
-		if ( ! empty( $entity['labels'][ $this->lang ]['value'] ) ) {
96
-			// Use the label if there is one.
97
-			return $entity['labels'][ $this->lang ]['value'];
98
-		}
99
-		// Or just use the ID.
100
-		return $entity['id'];
101
-	}
102
-
103
-	/**
104
-	 * @return string The Wikidata.org URL for this item.
105
-	 */
106
-	public function getWikidataUrl() {
107
-		return $this->wikidataUrlBase.$this->id;
108
-	}
109
-
110
-	/**
111
-	 * Wikiprojects list their properties like this:
112
-	 *
113
-	 *     {{List of properties/Header}}
114
-	 *     {{List of properties/Row|id=31|example-subject=Q923767|example-object=Q3331189}}
115
-	 *     </table>
116
-	 *
117
-	 * @param string $wikiProject The name of the WikiProject (must exist as a Wikidata page e.g.
118
-	 * [[Wikidata:$wikiProject]]).
119
-	 * @param string $type
120
-	 * @return array
121
-	 */
122
-	public function getStandardProperties( $wikiProject = 'WikiProject_Books', $type = 'work' ) {
123
-		if ( $type !== 'work' ) {
124
-			$type = 'edition';
125
-		}
126
-		$cacheKey = $type . '_item_property_IDs';
127
-		if ( $this->cache->hasItem( $cacheKey ) ) {
128
-			$propIds = $this->cache->getItem( $cacheKey )->get();
129
-		} else {
130
-			$domCrawler = new Crawler();
131
-			$wikiProjectUrl = 'https://www.wikidata.org/wiki/Wikidata:' . $wikiProject;
132
-			$domCrawler->addHtmlContent( file_get_contents( $wikiProjectUrl ) );
133
-			$propAncors = "//h3/span[@id='" . ucfirst( $type ) . "_item_properties']/../following-sibling::table[1]//td[2]/a";
134
-			$propCells = $domCrawler->filterXPath( $propAncors );
135
-			$propIds = [];
136
-			$propCells->each( function ( Crawler $node, $i ) use ( &$propIds ) {
137
-				$propId = $node->text();
138
-				$propIds[] = $propId;
139
-			} );
140
-			$cacheItem = $this->cache->getItem( $cacheKey )
141
-				->expiresAfter( new DateInterval( 'PT1H' ) )
142
-				->set( $propIds );
143
-			$this->cache->save( $cacheItem );
144
-		}
145
-		$workProperties = [];
146
-		foreach ( $propIds as $propId ) {
147
-			$workProperties[] = self::factory( $propId, $this->lang, $this->cache );
148
-		}
149
-
150
-		return $workProperties;
151
-	}
152
-
153
-	/**
154
-	 * @param string $propertyId
155
-	 * @return bool|Time[]
156
-	 */
157
-	public function getPropertyOfTypeTime( $propertyId ) {
158
-		$times = [];
159
-		$entity = $this->getEntity();
160
-		if ( !isset( $entity['claims'][$propertyId] ) ) {
161
-			// No statements for this property.
162
-			return $times;
163
-		}
164
-		// print_r($entity['claims'][$propertyId]);exit();
165
-		foreach ( $entity['claims'][$propertyId] as $claim ) {
166
-			// print_r($claim);
167
-			$times[] = new Time( $claim, $this->lang, $this->cache );
16
+    const PROP_INSTANCE_OF = 'P31';
17
+    const PROP_TITLE = 'P1476';
18
+    const PROP_IMAGE = 'P18';
19
+    const PROP_AUTHOR = 'P50';
20
+
21
+    /** @var string */
22
+    protected $id;
23
+
24
+    /** @var MediawikiApi */
25
+    protected $wdApi;
26
+
27
+    /** @var string */
28
+    protected $lang;
29
+
30
+    /** @var CacheItemPoolInterface */
31
+    protected $cache;
32
+
33
+    /** @var string The base URL of Wikidata, with trailing slash. */
34
+    protected $wikidataUrlBase = 'https://www.wikidata.org/wiki/';
35
+
36
+    private function __construct( $id, $lang, CacheItemPoolInterface $cache ) {
37
+        if ( !is_string( $id ) || preg_match( '/[QP][0-9]*/i', $id ) !== 1 ) {
38
+            throw new Exception( "Not a valid ID: " . var_export( $id, true ) );
39
+        }
40
+        $this->id = $id;
41
+        $this->wdApi = new MediawikiApi( 'https://www.wikidata.org/w/api.php' );
42
+        $this->entities = [];
43
+        $this->lang = $lang;
44
+        $this->cache = $cache;
45
+    }
46
+
47
+    /**
48
+     * Create a new Item object with class based on the item's 'instance of' statement.
49
+     *
50
+     * @param string $id The item ID (Q-number).
51
+     * @param string $lang The language code.
52
+     * @param CacheItemPoolInterface $cache The cache to use.
53
+     * @return Item
54
+     */
55
+    public static function factory( $id, $lang, CacheItemPoolInterface $cache ) {
56
+        $item = new Item( $id, $lang, $cache );
57
+        foreach ( $item->getPropertyOfTypeItem( self::PROP_INSTANCE_OF ) as $instanceOf ) {
58
+            // Try to find a class mating the 'instance of' name.
59
+            $possibleBaseClassName = Str::toCamelCase( $instanceOf->getItem()->getLabel() );
60
+            $possibleClassName = __NAMESPACE__ . '\\Items\\' . $possibleBaseClassName;
61
+            if ( class_exists( $possibleClassName ) ) {
62
+                // This won't re-request the metadata, because that's cached.
63
+                $specificItem = new $possibleClassName( $id, $lang, $cache );
64
+                return $specificItem;
65
+            }
66
+        }
67
+
68
+        // If we're here, just leave it as a basic Item.
69
+        $item->setCache( $cache );
70
+        return $item;
71
+    }
72
+
73
+    /**
74
+     * @param CacheItemPoolInterface $cache The cache to use.
75
+     */
76
+    public function setCache( CacheItemPoolInterface $cache ) {
77
+        $this->cache = $cache;
78
+    }
79
+
80
+    /**
81
+     * Get the ID (Q-number) of this item.
82
+     * @return string|bool The ID or false if it couldn't be determined.
83
+     */
84
+    public function getId() {
85
+        $entity = $this->getEntity( $this->id );
86
+        return isset( $entity['id'] ) ? $entity['id'] : false;
87
+    }
88
+
89
+    /**
90
+     * Get this item's label.
91
+     * @return string
92
+     */
93
+    public function getLabel() {
94
+        $entity = $this->getEntity( $this->id );
95
+        if ( ! empty( $entity['labels'][ $this->lang ]['value'] ) ) {
96
+            // Use the label if there is one.
97
+            return $entity['labels'][ $this->lang ]['value'];
98
+        }
99
+        // Or just use the ID.
100
+        return $entity['id'];
101
+    }
102
+
103
+    /**
104
+     * @return string The Wikidata.org URL for this item.
105
+     */
106
+    public function getWikidataUrl() {
107
+        return $this->wikidataUrlBase.$this->id;
108
+    }
109
+
110
+    /**
111
+     * Wikiprojects list their properties like this:
112
+     *
113
+     *     {{List of properties/Header}}
114
+     *     {{List of properties/Row|id=31|example-subject=Q923767|example-object=Q3331189}}
115
+     *     </table>
116
+     *
117
+     * @param string $wikiProject The name of the WikiProject (must exist as a Wikidata page e.g.
118
+     * [[Wikidata:$wikiProject]]).
119
+     * @param string $type
120
+     * @return array
121
+     */
122
+    public function getStandardProperties( $wikiProject = 'WikiProject_Books', $type = 'work' ) {
123
+        if ( $type !== 'work' ) {
124
+            $type = 'edition';
125
+        }
126
+        $cacheKey = $type . '_item_property_IDs';
127
+        if ( $this->cache->hasItem( $cacheKey ) ) {
128
+            $propIds = $this->cache->getItem( $cacheKey )->get();
129
+        } else {
130
+            $domCrawler = new Crawler();
131
+            $wikiProjectUrl = 'https://www.wikidata.org/wiki/Wikidata:' . $wikiProject;
132
+            $domCrawler->addHtmlContent( file_get_contents( $wikiProjectUrl ) );
133
+            $propAncors = "//h3/span[@id='" . ucfirst( $type ) . "_item_properties']/../following-sibling::table[1]//td[2]/a";
134
+            $propCells = $domCrawler->filterXPath( $propAncors );
135
+            $propIds = [];
136
+            $propCells->each( function ( Crawler $node, $i ) use ( &$propIds ) {
137
+                $propId = $node->text();
138
+                $propIds[] = $propId;
139
+            } );
140
+            $cacheItem = $this->cache->getItem( $cacheKey )
141
+                ->expiresAfter( new DateInterval( 'PT1H' ) )
142
+                ->set( $propIds );
143
+            $this->cache->save( $cacheItem );
144
+        }
145
+        $workProperties = [];
146
+        foreach ( $propIds as $propId ) {
147
+            $workProperties[] = self::factory( $propId, $this->lang, $this->cache );
148
+        }
149
+
150
+        return $workProperties;
151
+    }
152
+
153
+    /**
154
+     * @param string $propertyId
155
+     * @return bool|Time[]
156
+     */
157
+    public function getPropertyOfTypeTime( $propertyId ) {
158
+        $times = [];
159
+        $entity = $this->getEntity();
160
+        if ( !isset( $entity['claims'][$propertyId] ) ) {
161
+            // No statements for this property.
162
+            return $times;
163
+        }
164
+        // print_r($entity['claims'][$propertyId]);exit();
165
+        foreach ( $entity['claims'][$propertyId] as $claim ) {
166
+            // print_r($claim);
167
+            $times[] = new Time( $claim, $this->lang, $this->cache );
168 168
 //
169 169
 // $timeValue = $claim['datavalue']['value']['time'];
170 170
 // // Ugly workaround for imprecise dates. :-(
@@ -174,281 +174,281 @@  discard block
 block discarded – undo
174 174
 // }
175 175
 // $time = strtotime($timeValue);
176 176
 // return date($dateFormat, $time);
177
-			// }
178
-		}
179
-		return $times;
180
-	}
181
-
182
-	/**
183
-	 * Get the Item that is referred to by the specified item's property.
184
-	 *
185
-	 * @param string $propertyId
186
-	 *
187
-	 * @return \Samwilson\SimpleWikidata\Properties\Item[]
188
-	 */
189
-	public function getPropertyOfTypeItem( $propertyId ) {
190
-		$entity = $this->getEntity( $this->id );
191
-		if ( !isset( $entity['claims'][$propertyId] ) ) {
192
-			return [];
193
-		}
194
-		$items = [];
195
-		foreach ( $entity['claims'][$propertyId] as $claim ) {
196
-			$items[] = new Properties\Item( $claim, $this->lang, $this->cache );
197
-		}
198
-
199
-		return $items;
200
-	}
201
-
202
-	public function setPropertyOfTypeItem( $property, $itemId ) {
203
-		$itemIdNumeric = substr( $itemId, 1 );
204
-
205
-		// First see if this property already exists, and that it is different from what's being set.
206
-		$entity = $this->getEntity( $this->id );
207
-		if ( !empty( $entity['claims'][$property] ) ) {
208
-			// Get the first claim, and update it if necessary.
209
-			$claim = array_shift( $entity['claims'][$property] );
210
-			if ( $claim['mainsnak']['datavalue']['value']['id'] == $itemId ) {
211
-				// Already is the required value, no need to change.
212
-				return;
213
-			}
214
-			$claim['mainsnak']['datavalue']['value']['id'] = $itemId;
215
-			$claim['mainsnak']['datavalue']['value']['numeric-id'] = $itemIdNumeric;
216
-			$apiParams = [
217
-				'action' => 'wbsetclaim',
218
-				'claim' => json_encode( $claim ),
219
-			];
220
-		}
221
-
222
-		// If no claim was found (and modified) above, create a new claim.
223
-		if ( !isset( $apiParams ) ) {
224
-			$apiParams = [
225
-				'action' => 'wbcreateclaim',
226
-				'entity' => $this->getId(),
227
-				'property' => $property,
228
-				'snaktype' => 'value',
229
-				'value' => json_encode( [ 'entity-type' => 'item', 'numeric-id' => $itemIdNumeric ] ),
230
-			];
231
-		}
232
-
233
-		// @TODO Save the property.
234
-
235
-		// Clear the cache.
236
-		$this->cache->deleteItem( $this->getEntityCacheKey( $this->id ) );
237
-	}
238
-
239
-	public function getPropertyOfTypeUrl( $entityId, $propertyId ) {
240
-		$entity = $this->getEntity( $entityId );
241
-		if ( !isset( $entity['claims'][$propertyId] ) ) {
242
-			return false;
243
-		}
244
-		$urls = [];
245
-		foreach ( $entity['claims'][$propertyId] as $claim ) {
246
-			$urls[] = $claim['mainsnak']['datavalue']['value'];
247
-		}
248
-
249
-		return $urls;
250
-	}
251
-
252
-	public function getPropertyOfTypeExternalIdentifier( $entityId, $propertyId ) {
253
-		$entity = $this->getEntity( $entityId );
254
-		if ( !isset( $entity['claims'][$propertyId] ) ) {
255
-			return false;
256
-		}
257
-		$idents = [];
258
-		foreach ( $entity['claims'][$propertyId] as $claim ) {
259
-			$qualifiers = [];
260
-			if ( !isset( $claim['qualifiers'] ) ) {
261
-				continue;
262
-			}
263
-			foreach ( $claim['qualifiers'] as $qualsInfo ) {
264
-				foreach ( $qualsInfo as $qualInfo ) {
265
-					$qualProp = self::factory( $qualInfo['property'], $this->lang, $this->cache );
266
-					$propLabel = $qualProp->getLabel();
267
-					if ( !isset( $qualifiers[$propLabel] ) ) {
268
-						$qualifiers[$propLabel] = [];
269
-					}
270
-					$qualifiers[$propLabel][] = $qualInfo['datavalue']['value'];
271
-				}
272
-			}
273
-			$idents[] = [
274
-				'qualifiers' => $qualifiers,
275
-				'value' => $claim['mainsnak']['datavalue']['value'],
276
-			];
277
-		}
278
-
279
-		return $idents;
280
-	}
281
-
282
-	/**
283
-	 * Get a single-valued text property.
284
-	 * @param string $property One of the PROP_* constants.
285
-	 * @return string|bool The value, or false if it can't be found.
286
-	 */
287
-	public function getPropertyOfTypeText( $property ) {
288
-		$entity = $this->getEntity( $this->id );
289
-		if ( isset( $entity['claims'][$property] ) ) {
290
-			// Use the first title.
291
-			foreach ( $entity['claims'][$property] as $t ) {
292
-				if ( !isset( $t['mainsnak']['datavalue']['value']['language'] ) ) {
293
-					var_dump( $t['mainsnak']['datavalue']['value'] );
294
-					exit();
295
-				}
296
-				if ( $t['mainsnak']['datavalue']['value']['language'] == $this->lang
297
-					&& !empty( $t['mainsnak']['datavalue']['value']['text'] )
298
-				) {
299
-					return $t['mainsnak']['datavalue']['value']['text'];
300
-				}
301
-			}
302
-		}
303
-		return false;
304
-	}
305
-
306
-	/**
307
-	 * Literal data field for a quantity that relates to some kind of well-defined unit. The actual unit goes in the data values that is entered.
308
-	 *   - amount – implicit part of the string (mapping of unit prefix is unclear)
309
-	 *   - unit – implicit part of the string that defaults to "1" (mapping to standardizing body is unclear)
310
-	 *   - upperbound - quantity's upper bound
311
-	 *   - lowerbound - quantity's lower bound
312
-	 * @param $property
313
-	 * @return mixed[]|bool If it's not false it's an array with 'amount', 'unit', etc.
314
-	 */
315
-	public function getPropertyOfTypeQuantity( $property ) {
316
-		$quantities = [];
317
-		$entity = $this->getEntity( $this->id );
318
-		if ( !isset( $entity['claims'][$property] ) ) {
319
-			return false;
320
-		}
321
-		foreach ( $entity['claims'][$property] as $t ) {
322
-			$quantity = $t['mainsnak']['datavalue']['value'];
323
-			$unitId = substr( $quantity['unit'], strlen( $this->wikidataUrlBase ) + 1 );
324
-			$quantity['unit'] = self::factory( $unitId, $this->lang, $this->cache );
325
-			$quantities[] = $quantity;
326
-		}
327
-		return $quantities;
328
-	}
329
-
330
-	/**
331
-	 * Set a single-valued text property.
332
-	 * @param string $property One of the PROP_* constants.
333
-	 * @param string $value The value.
334
-	 */
335
-	public function setPropertyOfTypeText( $property, $value ) {
336
-		// First see if this property already exists, and that it is different from what's being set.
337
-		$entity = $this->getEntity( $this->id );
338
-		if ( !empty( $entity['claims'][$property] ) ) {
339
-			// Find this language's claim (if there is one).
340
-			foreach ( $entity['claims'][$property] as $claim ) {
341
-				if ( $claim['mainsnak']['datavalue']['value']['language'] == $this->lang ) {
342
-					// Modify this claim's text value.
343
-					$titleClaim = $claim;
344
-					$titleClaim['mainsnak']['datavalue']['value']['text'] = $value;
345
-					$setTitleParams = [
346
-						'action' => 'wbsetclaim',
347
-						'claim' => \GuzzleHttp\json_encode( $titleClaim ),
348
-					];
349
-					continue;
350
-				}
351
-			}
352
-		}
353
-
354
-		// If no claim was found (and modified) above, create a new claim.
355
-		if ( !isset( $setTitleParams ) ) {
356
-			$setTitleParams = [
357
-				'action' => 'wbcreateclaim',
358
-				'entity' => $this->getId(),
359
-				'property' => $property,
360
-				'snaktype' => 'value',
361
-				'value' => \GuzzleHttp\json_encode( [ 'text' => $value, 'language' => $this->lang ] ),
362
-			];
363
-		}
364
-
365
-		// Save the property.
366
-		$wdWpOauth = new WdWpOauth();
367
-		$wdWpOauth->makeCall( $setTitleParams, true );
368
-
369
-		// Clear the cache.
370
-		$this->cache->deleteItem( $this->getEntityCacheKey( $this->id ) );
371
-	}
372
-
373
-	public function getInstanceOf() {
374
-		$instancesOf = $this->getPropertyOfTypeItem( $this->getId(), self::PROP_INSTANCE_OF );
375
-		return array_shift( $instancesOf );
376
-	}
377
-
378
-	/**
379
-	 * Does this item exist?
380
-	 * @return bool
381
-	 */
382
-	public function exists() {
383
-		return $this->getId() !== false;
384
-	}
385
-
386
-	public function getWikipediaIntro() {
387
-		$cacheKey = 'wikipedia-intro-' . $this->id . $this->lang;
388
-		if ( $this->cache->hasItem( $cacheKey ) ) {
389
-			return $this->cache->getItem( $cacheKey )->get();
390
-		}
391
-		$entity = $this->getEntity( $this->id );
392
-		if ( !isset( $entity['sitelinks'] ) ) {
393
-			return [];
394
-		}
395
-		foreach ( $entity['sitelinks'] as $sitelink ) {
396
-			if ( $sitelink['site'] == $this->lang . 'wiki' ) {
397
-				$api = new MediawikiApi( 'https://' . $this->lang . '.wikipedia.org/w/api.php' );
398
-				$req = new SimpleRequest( 'query', [
399
-					'prop' => 'extracts',
400
-					'exintro' => true,
401
-					'titles' => $sitelink['title'],
402
-				] );
403
-				$response = $api->getRequest( $req );
404
-				$page = array_shift( $response['query']['pages'] );
405
-				$out = [
406
-					'title' => $page['title'],
407
-					'html' => $page['extract'],
408
-				];
409
-				$cacheItem = $this->cache->getItem( $cacheKey )
410
-					->expiresAfter( new DateInterval( 'P1D' ) )
411
-					->set( $out );
412
-				$this->cache->save( $cacheItem );
413
-
414
-				return $out;
415
-			}
416
-		}
417
-
418
-		return [];
419
-	}
420
-
421
-	/**
422
-	 * Get the raw entity data from the 'wbgetentities' API call.
423
-	 * @param string $id
424
-	 * @param bool $ignoreCache
425
-	 * @return bool
426
-	 */
427
-	public function getEntity( $id = null, $ignoreCache = false ) {
428
-		$idActual = $id ?: $this->id;
429
-		$cacheKey = $this->getEntityCacheKey( $idActual );
430
-		if ( !$ignoreCache && $this->cache->hasItem( $cacheKey ) ) {
431
-			return $this->cache->getItem( $cacheKey )->get();
432
-		}
433
-		$metadataRequest = new SimpleRequest( 'wbgetentities', [ 'ids' => $idActual ] );
434
-		$itemResult = $this->wdApi->getRequest( $metadataRequest );
435
-		if ( !isset( $itemResult['success'] ) || !isset( $itemResult['entities'][$id] ) ) {
436
-			return false;
437
-		}
438
-		$metadata = $itemResult['entities'][$idActual];
439
-		$cacheItem = $this->cache->getItem( $cacheKey )
440
-			->expiresAfter( new DateInterval( 'PT10M' ) )
441
-			->set( $metadata );
442
-		$this->cache->save( $cacheItem );
443
-		return $metadata;
444
-	}
445
-
446
-	/**
447
-	 * @param $id
448
-	 *
449
-	 * @return string
450
-	 */
451
-	protected function getEntityCacheKey( $id ) {
452
-		return 'entities' . $id;
453
-	}
177
+            // }
178
+        }
179
+        return $times;
180
+    }
181
+
182
+    /**
183
+     * Get the Item that is referred to by the specified item's property.
184
+     *
185
+     * @param string $propertyId
186
+     *
187
+     * @return \Samwilson\SimpleWikidata\Properties\Item[]
188
+     */
189
+    public function getPropertyOfTypeItem( $propertyId ) {
190
+        $entity = $this->getEntity( $this->id );
191
+        if ( !isset( $entity['claims'][$propertyId] ) ) {
192
+            return [];
193
+        }
194
+        $items = [];
195
+        foreach ( $entity['claims'][$propertyId] as $claim ) {
196
+            $items[] = new Properties\Item( $claim, $this->lang, $this->cache );
197
+        }
198
+
199
+        return $items;
200
+    }
201
+
202
+    public function setPropertyOfTypeItem( $property, $itemId ) {
203
+        $itemIdNumeric = substr( $itemId, 1 );
204
+
205
+        // First see if this property already exists, and that it is different from what's being set.
206
+        $entity = $this->getEntity( $this->id );
207
+        if ( !empty( $entity['claims'][$property] ) ) {
208
+            // Get the first claim, and update it if necessary.
209
+            $claim = array_shift( $entity['claims'][$property] );
210
+            if ( $claim['mainsnak']['datavalue']['value']['id'] == $itemId ) {
211
+                // Already is the required value, no need to change.
212
+                return;
213
+            }
214
+            $claim['mainsnak']['datavalue']['value']['id'] = $itemId;
215
+            $claim['mainsnak']['datavalue']['value']['numeric-id'] = $itemIdNumeric;
216
+            $apiParams = [
217
+                'action' => 'wbsetclaim',
218
+                'claim' => json_encode( $claim ),
219
+            ];
220
+        }
221
+
222
+        // If no claim was found (and modified) above, create a new claim.
223
+        if ( !isset( $apiParams ) ) {
224
+            $apiParams = [
225
+                'action' => 'wbcreateclaim',
226
+                'entity' => $this->getId(),
227
+                'property' => $property,
228
+                'snaktype' => 'value',
229
+                'value' => json_encode( [ 'entity-type' => 'item', 'numeric-id' => $itemIdNumeric ] ),
230
+            ];
231
+        }
232
+
233
+        // @TODO Save the property.
234
+
235
+        // Clear the cache.
236
+        $this->cache->deleteItem( $this->getEntityCacheKey( $this->id ) );
237
+    }
238
+
239
+    public function getPropertyOfTypeUrl( $entityId, $propertyId ) {
240
+        $entity = $this->getEntity( $entityId );
241
+        if ( !isset( $entity['claims'][$propertyId] ) ) {
242
+            return false;
243
+        }
244
+        $urls = [];
245
+        foreach ( $entity['claims'][$propertyId] as $claim ) {
246
+            $urls[] = $claim['mainsnak']['datavalue']['value'];
247
+        }
248
+
249
+        return $urls;
250
+    }
251
+
252
+    public function getPropertyOfTypeExternalIdentifier( $entityId, $propertyId ) {
253
+        $entity = $this->getEntity( $entityId );
254
+        if ( !isset( $entity['claims'][$propertyId] ) ) {
255
+            return false;
256
+        }
257
+        $idents = [];
258
+        foreach ( $entity['claims'][$propertyId] as $claim ) {
259
+            $qualifiers = [];
260
+            if ( !isset( $claim['qualifiers'] ) ) {
261
+                continue;
262
+            }
263
+            foreach ( $claim['qualifiers'] as $qualsInfo ) {
264
+                foreach ( $qualsInfo as $qualInfo ) {
265
+                    $qualProp = self::factory( $qualInfo['property'], $this->lang, $this->cache );
266
+                    $propLabel = $qualProp->getLabel();
267
+                    if ( !isset( $qualifiers[$propLabel] ) ) {
268
+                        $qualifiers[$propLabel] = [];
269
+                    }
270
+                    $qualifiers[$propLabel][] = $qualInfo['datavalue']['value'];
271
+                }
272
+            }
273
+            $idents[] = [
274
+                'qualifiers' => $qualifiers,
275
+                'value' => $claim['mainsnak']['datavalue']['value'],
276
+            ];
277
+        }
278
+
279
+        return $idents;
280
+    }
281
+
282
+    /**
283
+     * Get a single-valued text property.
284
+     * @param string $property One of the PROP_* constants.
285
+     * @return string|bool The value, or false if it can't be found.
286
+     */
287
+    public function getPropertyOfTypeText( $property ) {
288
+        $entity = $this->getEntity( $this->id );
289
+        if ( isset( $entity['claims'][$property] ) ) {
290
+            // Use the first title.
291
+            foreach ( $entity['claims'][$property] as $t ) {
292
+                if ( !isset( $t['mainsnak']['datavalue']['value']['language'] ) ) {
293
+                    var_dump( $t['mainsnak']['datavalue']['value'] );
294
+                    exit();
295
+                }
296
+                if ( $t['mainsnak']['datavalue']['value']['language'] == $this->lang
297
+                    && !empty( $t['mainsnak']['datavalue']['value']['text'] )
298
+                ) {
299
+                    return $t['mainsnak']['datavalue']['value']['text'];
300
+                }
301
+            }
302
+        }
303
+        return false;
304
+    }
305
+
306
+    /**
307
+     * Literal data field for a quantity that relates to some kind of well-defined unit. The actual unit goes in the data values that is entered.
308
+     *   - amount – implicit part of the string (mapping of unit prefix is unclear)
309
+     *   - unit – implicit part of the string that defaults to "1" (mapping to standardizing body is unclear)
310
+     *   - upperbound - quantity's upper bound
311
+     *   - lowerbound - quantity's lower bound
312
+     * @param $property
313
+     * @return mixed[]|bool If it's not false it's an array with 'amount', 'unit', etc.
314
+     */
315
+    public function getPropertyOfTypeQuantity( $property ) {
316
+        $quantities = [];
317
+        $entity = $this->getEntity( $this->id );
318
+        if ( !isset( $entity['claims'][$property] ) ) {
319
+            return false;
320
+        }
321
+        foreach ( $entity['claims'][$property] as $t ) {
322
+            $quantity = $t['mainsnak']['datavalue']['value'];
323
+            $unitId = substr( $quantity['unit'], strlen( $this->wikidataUrlBase ) + 1 );
324
+            $quantity['unit'] = self::factory( $unitId, $this->lang, $this->cache );
325
+            $quantities[] = $quantity;
326
+        }
327
+        return $quantities;
328
+    }
329
+
330
+    /**
331
+     * Set a single-valued text property.
332
+     * @param string $property One of the PROP_* constants.
333
+     * @param string $value The value.
334
+     */
335
+    public function setPropertyOfTypeText( $property, $value ) {
336
+        // First see if this property already exists, and that it is different from what's being set.
337
+        $entity = $this->getEntity( $this->id );
338
+        if ( !empty( $entity['claims'][$property] ) ) {
339
+            // Find this language's claim (if there is one).
340
+            foreach ( $entity['claims'][$property] as $claim ) {
341
+                if ( $claim['mainsnak']['datavalue']['value']['language'] == $this->lang ) {
342
+                    // Modify this claim's text value.
343
+                    $titleClaim = $claim;
344
+                    $titleClaim['mainsnak']['datavalue']['value']['text'] = $value;
345
+                    $setTitleParams = [
346
+                        'action' => 'wbsetclaim',
347
+                        'claim' => \GuzzleHttp\json_encode( $titleClaim ),
348
+                    ];
349
+                    continue;
350
+                }
351
+            }
352
+        }
353
+
354
+        // If no claim was found (and modified) above, create a new claim.
355
+        if ( !isset( $setTitleParams ) ) {
356
+            $setTitleParams = [
357
+                'action' => 'wbcreateclaim',
358
+                'entity' => $this->getId(),
359
+                'property' => $property,
360
+                'snaktype' => 'value',
361
+                'value' => \GuzzleHttp\json_encode( [ 'text' => $value, 'language' => $this->lang ] ),
362
+            ];
363
+        }
364
+
365
+        // Save the property.
366
+        $wdWpOauth = new WdWpOauth();
367
+        $wdWpOauth->makeCall( $setTitleParams, true );
368
+
369
+        // Clear the cache.
370
+        $this->cache->deleteItem( $this->getEntityCacheKey( $this->id ) );
371
+    }
372
+
373
+    public function getInstanceOf() {
374
+        $instancesOf = $this->getPropertyOfTypeItem( $this->getId(), self::PROP_INSTANCE_OF );
375
+        return array_shift( $instancesOf );
376
+    }
377
+
378
+    /**
379
+     * Does this item exist?
380
+     * @return bool
381
+     */
382
+    public function exists() {
383
+        return $this->getId() !== false;
384
+    }
385
+
386
+    public function getWikipediaIntro() {
387
+        $cacheKey = 'wikipedia-intro-' . $this->id . $this->lang;
388
+        if ( $this->cache->hasItem( $cacheKey ) ) {
389
+            return $this->cache->getItem( $cacheKey )->get();
390
+        }
391
+        $entity = $this->getEntity( $this->id );
392
+        if ( !isset( $entity['sitelinks'] ) ) {
393
+            return [];
394
+        }
395
+        foreach ( $entity['sitelinks'] as $sitelink ) {
396
+            if ( $sitelink['site'] == $this->lang . 'wiki' ) {
397
+                $api = new MediawikiApi( 'https://' . $this->lang . '.wikipedia.org/w/api.php' );
398
+                $req = new SimpleRequest( 'query', [
399
+                    'prop' => 'extracts',
400
+                    'exintro' => true,
401
+                    'titles' => $sitelink['title'],
402
+                ] );
403
+                $response = $api->getRequest( $req );
404
+                $page = array_shift( $response['query']['pages'] );
405
+                $out = [
406
+                    'title' => $page['title'],
407
+                    'html' => $page['extract'],
408
+                ];
409
+                $cacheItem = $this->cache->getItem( $cacheKey )
410
+                    ->expiresAfter( new DateInterval( 'P1D' ) )
411
+                    ->set( $out );
412
+                $this->cache->save( $cacheItem );
413
+
414
+                return $out;
415
+            }
416
+        }
417
+
418
+        return [];
419
+    }
420
+
421
+    /**
422
+     * Get the raw entity data from the 'wbgetentities' API call.
423
+     * @param string $id
424
+     * @param bool $ignoreCache
425
+     * @return bool
426
+     */
427
+    public function getEntity( $id = null, $ignoreCache = false ) {
428
+        $idActual = $id ?: $this->id;
429
+        $cacheKey = $this->getEntityCacheKey( $idActual );
430
+        if ( !$ignoreCache && $this->cache->hasItem( $cacheKey ) ) {
431
+            return $this->cache->getItem( $cacheKey )->get();
432
+        }
433
+        $metadataRequest = new SimpleRequest( 'wbgetentities', [ 'ids' => $idActual ] );
434
+        $itemResult = $this->wdApi->getRequest( $metadataRequest );
435
+        if ( !isset( $itemResult['success'] ) || !isset( $itemResult['entities'][$id] ) ) {
436
+            return false;
437
+        }
438
+        $metadata = $itemResult['entities'][$idActual];
439
+        $cacheItem = $this->cache->getItem( $cacheKey )
440
+            ->expiresAfter( new DateInterval( 'PT10M' ) )
441
+            ->set( $metadata );
442
+        $this->cache->save( $cacheItem );
443
+        return $metadata;
444
+    }
445
+
446
+    /**
447
+     * @param $id
448
+     *
449
+     * @return string
450
+     */
451
+    protected function getEntityCacheKey( $id ) {
452
+        return 'entities' . $id;
453
+    }
454 454
 }
Please login to merge, or discard this patch.
Spacing   +117 added lines, -117 removed lines patch added patch discarded remove patch
@@ -33,12 +33,12 @@  discard block
 block discarded – undo
33 33
 	/** @var string The base URL of Wikidata, with trailing slash. */
34 34
 	protected $wikidataUrlBase = 'https://www.wikidata.org/wiki/';
35 35
 
36
-	private function __construct( $id, $lang, CacheItemPoolInterface $cache ) {
37
-		if ( !is_string( $id ) || preg_match( '/[QP][0-9]*/i', $id ) !== 1 ) {
38
-			throw new Exception( "Not a valid ID: " . var_export( $id, true ) );
36
+	private function __construct($id, $lang, CacheItemPoolInterface $cache) {
37
+		if (!is_string($id) || preg_match('/[QP][0-9]*/i', $id) !== 1) {
38
+			throw new Exception("Not a valid ID: " . var_export($id, true));
39 39
 		}
40 40
 		$this->id = $id;
41
-		$this->wdApi = new MediawikiApi( 'https://www.wikidata.org/w/api.php' );
41
+		$this->wdApi = new MediawikiApi('https://www.wikidata.org/w/api.php');
42 42
 		$this->entities = [];
43 43
 		$this->lang = $lang;
44 44
 		$this->cache = $cache;
@@ -52,28 +52,28 @@  discard block
 block discarded – undo
52 52
 	 * @param CacheItemPoolInterface $cache The cache to use.
53 53
 	 * @return Item
54 54
 	 */
55
-	public static function factory( $id, $lang, CacheItemPoolInterface $cache ) {
56
-		$item = new Item( $id, $lang, $cache );
57
-		foreach ( $item->getPropertyOfTypeItem( self::PROP_INSTANCE_OF ) as $instanceOf ) {
55
+	public static function factory($id, $lang, CacheItemPoolInterface $cache) {
56
+		$item = new Item($id, $lang, $cache);
57
+		foreach ($item->getPropertyOfTypeItem(self::PROP_INSTANCE_OF) as $instanceOf) {
58 58
 			// Try to find a class mating the 'instance of' name.
59
-			$possibleBaseClassName = Str::toCamelCase( $instanceOf->getItem()->getLabel() );
59
+			$possibleBaseClassName = Str::toCamelCase($instanceOf->getItem()->getLabel());
60 60
 			$possibleClassName = __NAMESPACE__ . '\\Items\\' . $possibleBaseClassName;
61
-			if ( class_exists( $possibleClassName ) ) {
61
+			if (class_exists($possibleClassName)) {
62 62
 				// This won't re-request the metadata, because that's cached.
63
-				$specificItem = new $possibleClassName( $id, $lang, $cache );
63
+				$specificItem = new $possibleClassName($id, $lang, $cache);
64 64
 				return $specificItem;
65 65
 			}
66 66
 		}
67 67
 
68 68
 		// If we're here, just leave it as a basic Item.
69
-		$item->setCache( $cache );
69
+		$item->setCache($cache);
70 70
 		return $item;
71 71
 	}
72 72
 
73 73
 	/**
74 74
 	 * @param CacheItemPoolInterface $cache The cache to use.
75 75
 	 */
76
-	public function setCache( CacheItemPoolInterface $cache ) {
76
+	public function setCache(CacheItemPoolInterface $cache) {
77 77
 		$this->cache = $cache;
78 78
 	}
79 79
 
@@ -82,8 +82,8 @@  discard block
 block discarded – undo
82 82
 	 * @return string|bool The ID or false if it couldn't be determined.
83 83
 	 */
84 84
 	public function getId() {
85
-		$entity = $this->getEntity( $this->id );
86
-		return isset( $entity['id'] ) ? $entity['id'] : false;
85
+		$entity = $this->getEntity($this->id);
86
+		return isset($entity['id']) ? $entity['id'] : false;
87 87
 	}
88 88
 
89 89
 	/**
@@ -91,10 +91,10 @@  discard block
 block discarded – undo
91 91
 	 * @return string
92 92
 	 */
93 93
 	public function getLabel() {
94
-		$entity = $this->getEntity( $this->id );
95
-		if ( ! empty( $entity['labels'][ $this->lang ]['value'] ) ) {
94
+		$entity = $this->getEntity($this->id);
95
+		if (!empty($entity['labels'][$this->lang]['value'])) {
96 96
 			// Use the label if there is one.
97
-			return $entity['labels'][ $this->lang ]['value'];
97
+			return $entity['labels'][$this->lang]['value'];
98 98
 		}
99 99
 		// Or just use the ID.
100 100
 		return $entity['id'];
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 	 * @return string The Wikidata.org URL for this item.
105 105
 	 */
106 106
 	public function getWikidataUrl() {
107
-		return $this->wikidataUrlBase.$this->id;
107
+		return $this->wikidataUrlBase . $this->id;
108 108
 	}
109 109
 
110 110
 	/**
@@ -119,32 +119,32 @@  discard block
 block discarded – undo
119 119
 	 * @param string $type
120 120
 	 * @return array
121 121
 	 */
122
-	public function getStandardProperties( $wikiProject = 'WikiProject_Books', $type = 'work' ) {
123
-		if ( $type !== 'work' ) {
122
+	public function getStandardProperties($wikiProject = 'WikiProject_Books', $type = 'work') {
123
+		if ($type !== 'work') {
124 124
 			$type = 'edition';
125 125
 		}
126 126
 		$cacheKey = $type . '_item_property_IDs';
127
-		if ( $this->cache->hasItem( $cacheKey ) ) {
128
-			$propIds = $this->cache->getItem( $cacheKey )->get();
127
+		if ($this->cache->hasItem($cacheKey)) {
128
+			$propIds = $this->cache->getItem($cacheKey)->get();
129 129
 		} else {
130 130
 			$domCrawler = new Crawler();
131 131
 			$wikiProjectUrl = 'https://www.wikidata.org/wiki/Wikidata:' . $wikiProject;
132
-			$domCrawler->addHtmlContent( file_get_contents( $wikiProjectUrl ) );
133
-			$propAncors = "//h3/span[@id='" . ucfirst( $type ) . "_item_properties']/../following-sibling::table[1]//td[2]/a";
134
-			$propCells = $domCrawler->filterXPath( $propAncors );
132
+			$domCrawler->addHtmlContent(file_get_contents($wikiProjectUrl));
133
+			$propAncors = "//h3/span[@id='" . ucfirst($type) . "_item_properties']/../following-sibling::table[1]//td[2]/a";
134
+			$propCells = $domCrawler->filterXPath($propAncors);
135 135
 			$propIds = [];
136
-			$propCells->each( function ( Crawler $node, $i ) use ( &$propIds ) {
136
+			$propCells->each(function(Crawler $node, $i) use (&$propIds) {
137 137
 				$propId = $node->text();
138 138
 				$propIds[] = $propId;
139 139
 			} );
140
-			$cacheItem = $this->cache->getItem( $cacheKey )
141
-				->expiresAfter( new DateInterval( 'PT1H' ) )
142
-				->set( $propIds );
143
-			$this->cache->save( $cacheItem );
140
+			$cacheItem = $this->cache->getItem($cacheKey)
141
+				->expiresAfter(new DateInterval('PT1H'))
142
+				->set($propIds);
143
+			$this->cache->save($cacheItem);
144 144
 		}
145 145
 		$workProperties = [];
146
-		foreach ( $propIds as $propId ) {
147
-			$workProperties[] = self::factory( $propId, $this->lang, $this->cache );
146
+		foreach ($propIds as $propId) {
147
+			$workProperties[] = self::factory($propId, $this->lang, $this->cache);
148 148
 		}
149 149
 
150 150
 		return $workProperties;
@@ -154,17 +154,17 @@  discard block
 block discarded – undo
154 154
 	 * @param string $propertyId
155 155
 	 * @return bool|Time[]
156 156
 	 */
157
-	public function getPropertyOfTypeTime( $propertyId ) {
157
+	public function getPropertyOfTypeTime($propertyId) {
158 158
 		$times = [];
159 159
 		$entity = $this->getEntity();
160
-		if ( !isset( $entity['claims'][$propertyId] ) ) {
160
+		if (!isset($entity['claims'][$propertyId])) {
161 161
 			// No statements for this property.
162 162
 			return $times;
163 163
 		}
164 164
 		// print_r($entity['claims'][$propertyId]);exit();
165
-		foreach ( $entity['claims'][$propertyId] as $claim ) {
165
+		foreach ($entity['claims'][$propertyId] as $claim) {
166 166
 			// print_r($claim);
167
-			$times[] = new Time( $claim, $this->lang, $this->cache );
167
+			$times[] = new Time($claim, $this->lang, $this->cache);
168 168
 //
169 169
 // $timeValue = $claim['datavalue']['value']['time'];
170 170
 // // Ugly workaround for imprecise dates. :-(
@@ -186,28 +186,28 @@  discard block
 block discarded – undo
186 186
 	 *
187 187
 	 * @return \Samwilson\SimpleWikidata\Properties\Item[]
188 188
 	 */
189
-	public function getPropertyOfTypeItem( $propertyId ) {
190
-		$entity = $this->getEntity( $this->id );
191
-		if ( !isset( $entity['claims'][$propertyId] ) ) {
189
+	public function getPropertyOfTypeItem($propertyId) {
190
+		$entity = $this->getEntity($this->id);
191
+		if (!isset($entity['claims'][$propertyId])) {
192 192
 			return [];
193 193
 		}
194 194
 		$items = [];
195
-		foreach ( $entity['claims'][$propertyId] as $claim ) {
196
-			$items[] = new Properties\Item( $claim, $this->lang, $this->cache );
195
+		foreach ($entity['claims'][$propertyId] as $claim) {
196
+			$items[] = new Properties\Item($claim, $this->lang, $this->cache);
197 197
 		}
198 198
 
199 199
 		return $items;
200 200
 	}
201 201
 
202
-	public function setPropertyOfTypeItem( $property, $itemId ) {
203
-		$itemIdNumeric = substr( $itemId, 1 );
202
+	public function setPropertyOfTypeItem($property, $itemId) {
203
+		$itemIdNumeric = substr($itemId, 1);
204 204
 
205 205
 		// First see if this property already exists, and that it is different from what's being set.
206
-		$entity = $this->getEntity( $this->id );
207
-		if ( !empty( $entity['claims'][$property] ) ) {
206
+		$entity = $this->getEntity($this->id);
207
+		if (!empty($entity['claims'][$property])) {
208 208
 			// Get the first claim, and update it if necessary.
209
-			$claim = array_shift( $entity['claims'][$property] );
210
-			if ( $claim['mainsnak']['datavalue']['value']['id'] == $itemId ) {
209
+			$claim = array_shift($entity['claims'][$property]);
210
+			if ($claim['mainsnak']['datavalue']['value']['id'] == $itemId) {
211 211
 				// Already is the required value, no need to change.
212 212
 				return;
213 213
 			}
@@ -215,56 +215,56 @@  discard block
 block discarded – undo
215 215
 			$claim['mainsnak']['datavalue']['value']['numeric-id'] = $itemIdNumeric;
216 216
 			$apiParams = [
217 217
 				'action' => 'wbsetclaim',
218
-				'claim' => json_encode( $claim ),
218
+				'claim' => json_encode($claim),
219 219
 			];
220 220
 		}
221 221
 
222 222
 		// If no claim was found (and modified) above, create a new claim.
223
-		if ( !isset( $apiParams ) ) {
223
+		if (!isset($apiParams)) {
224 224
 			$apiParams = [
225 225
 				'action' => 'wbcreateclaim',
226 226
 				'entity' => $this->getId(),
227 227
 				'property' => $property,
228 228
 				'snaktype' => 'value',
229
-				'value' => json_encode( [ 'entity-type' => 'item', 'numeric-id' => $itemIdNumeric ] ),
229
+				'value' => json_encode(['entity-type' => 'item', 'numeric-id' => $itemIdNumeric]),
230 230
 			];
231 231
 		}
232 232
 
233 233
 		// @TODO Save the property.
234 234
 
235 235
 		// Clear the cache.
236
-		$this->cache->deleteItem( $this->getEntityCacheKey( $this->id ) );
236
+		$this->cache->deleteItem($this->getEntityCacheKey($this->id));
237 237
 	}
238 238
 
239
-	public function getPropertyOfTypeUrl( $entityId, $propertyId ) {
240
-		$entity = $this->getEntity( $entityId );
241
-		if ( !isset( $entity['claims'][$propertyId] ) ) {
239
+	public function getPropertyOfTypeUrl($entityId, $propertyId) {
240
+		$entity = $this->getEntity($entityId);
241
+		if (!isset($entity['claims'][$propertyId])) {
242 242
 			return false;
243 243
 		}
244 244
 		$urls = [];
245
-		foreach ( $entity['claims'][$propertyId] as $claim ) {
245
+		foreach ($entity['claims'][$propertyId] as $claim) {
246 246
 			$urls[] = $claim['mainsnak']['datavalue']['value'];
247 247
 		}
248 248
 
249 249
 		return $urls;
250 250
 	}
251 251
 
252
-	public function getPropertyOfTypeExternalIdentifier( $entityId, $propertyId ) {
253
-		$entity = $this->getEntity( $entityId );
254
-		if ( !isset( $entity['claims'][$propertyId] ) ) {
252
+	public function getPropertyOfTypeExternalIdentifier($entityId, $propertyId) {
253
+		$entity = $this->getEntity($entityId);
254
+		if (!isset($entity['claims'][$propertyId])) {
255 255
 			return false;
256 256
 		}
257 257
 		$idents = [];
258
-		foreach ( $entity['claims'][$propertyId] as $claim ) {
258
+		foreach ($entity['claims'][$propertyId] as $claim) {
259 259
 			$qualifiers = [];
260
-			if ( !isset( $claim['qualifiers'] ) ) {
260
+			if (!isset($claim['qualifiers'])) {
261 261
 				continue;
262 262
 			}
263
-			foreach ( $claim['qualifiers'] as $qualsInfo ) {
264
-				foreach ( $qualsInfo as $qualInfo ) {
265
-					$qualProp = self::factory( $qualInfo['property'], $this->lang, $this->cache );
263
+			foreach ($claim['qualifiers'] as $qualsInfo) {
264
+				foreach ($qualsInfo as $qualInfo) {
265
+					$qualProp = self::factory($qualInfo['property'], $this->lang, $this->cache);
266 266
 					$propLabel = $qualProp->getLabel();
267
-					if ( !isset( $qualifiers[$propLabel] ) ) {
267
+					if (!isset($qualifiers[$propLabel])) {
268 268
 						$qualifiers[$propLabel] = [];
269 269
 					}
270 270
 					$qualifiers[$propLabel][] = $qualInfo['datavalue']['value'];
@@ -284,17 +284,17 @@  discard block
 block discarded – undo
284 284
 	 * @param string $property One of the PROP_* constants.
285 285
 	 * @return string|bool The value, or false if it can't be found.
286 286
 	 */
287
-	public function getPropertyOfTypeText( $property ) {
288
-		$entity = $this->getEntity( $this->id );
289
-		if ( isset( $entity['claims'][$property] ) ) {
287
+	public function getPropertyOfTypeText($property) {
288
+		$entity = $this->getEntity($this->id);
289
+		if (isset($entity['claims'][$property])) {
290 290
 			// Use the first title.
291
-			foreach ( $entity['claims'][$property] as $t ) {
292
-				if ( !isset( $t['mainsnak']['datavalue']['value']['language'] ) ) {
293
-					var_dump( $t['mainsnak']['datavalue']['value'] );
291
+			foreach ($entity['claims'][$property] as $t) {
292
+				if (!isset($t['mainsnak']['datavalue']['value']['language'])) {
293
+					var_dump($t['mainsnak']['datavalue']['value']);
294 294
 					exit();
295 295
 				}
296
-				if ( $t['mainsnak']['datavalue']['value']['language'] == $this->lang
297
-					&& !empty( $t['mainsnak']['datavalue']['value']['text'] )
296
+				if ($t['mainsnak']['datavalue']['value']['language'] == $this->lang
297
+					&& !empty($t['mainsnak']['datavalue']['value']['text'])
298 298
 				) {
299 299
 					return $t['mainsnak']['datavalue']['value']['text'];
300 300
 				}
@@ -312,16 +312,16 @@  discard block
 block discarded – undo
312 312
 	 * @param $property
313 313
 	 * @return mixed[]|bool If it's not false it's an array with 'amount', 'unit', etc.
314 314
 	 */
315
-	public function getPropertyOfTypeQuantity( $property ) {
315
+	public function getPropertyOfTypeQuantity($property) {
316 316
 		$quantities = [];
317
-		$entity = $this->getEntity( $this->id );
318
-		if ( !isset( $entity['claims'][$property] ) ) {
317
+		$entity = $this->getEntity($this->id);
318
+		if (!isset($entity['claims'][$property])) {
319 319
 			return false;
320 320
 		}
321
-		foreach ( $entity['claims'][$property] as $t ) {
321
+		foreach ($entity['claims'][$property] as $t) {
322 322
 			$quantity = $t['mainsnak']['datavalue']['value'];
323
-			$unitId = substr( $quantity['unit'], strlen( $this->wikidataUrlBase ) + 1 );
324
-			$quantity['unit'] = self::factory( $unitId, $this->lang, $this->cache );
323
+			$unitId = substr($quantity['unit'], strlen($this->wikidataUrlBase) + 1);
324
+			$quantity['unit'] = self::factory($unitId, $this->lang, $this->cache);
325 325
 			$quantities[] = $quantity;
326 326
 		}
327 327
 		return $quantities;
@@ -332,19 +332,19 @@  discard block
 block discarded – undo
332 332
 	 * @param string $property One of the PROP_* constants.
333 333
 	 * @param string $value The value.
334 334
 	 */
335
-	public function setPropertyOfTypeText( $property, $value ) {
335
+	public function setPropertyOfTypeText($property, $value) {
336 336
 		// First see if this property already exists, and that it is different from what's being set.
337
-		$entity = $this->getEntity( $this->id );
338
-		if ( !empty( $entity['claims'][$property] ) ) {
337
+		$entity = $this->getEntity($this->id);
338
+		if (!empty($entity['claims'][$property])) {
339 339
 			// Find this language's claim (if there is one).
340
-			foreach ( $entity['claims'][$property] as $claim ) {
341
-				if ( $claim['mainsnak']['datavalue']['value']['language'] == $this->lang ) {
340
+			foreach ($entity['claims'][$property] as $claim) {
341
+				if ($claim['mainsnak']['datavalue']['value']['language'] == $this->lang) {
342 342
 					// Modify this claim's text value.
343 343
 					$titleClaim = $claim;
344 344
 					$titleClaim['mainsnak']['datavalue']['value']['text'] = $value;
345 345
 					$setTitleParams = [
346 346
 						'action' => 'wbsetclaim',
347
-						'claim' => \GuzzleHttp\json_encode( $titleClaim ),
347
+						'claim' => \GuzzleHttp\json_encode($titleClaim),
348 348
 					];
349 349
 					continue;
350 350
 				}
@@ -352,27 +352,27 @@  discard block
 block discarded – undo
352 352
 		}
353 353
 
354 354
 		// If no claim was found (and modified) above, create a new claim.
355
-		if ( !isset( $setTitleParams ) ) {
355
+		if (!isset($setTitleParams)) {
356 356
 			$setTitleParams = [
357 357
 				'action' => 'wbcreateclaim',
358 358
 				'entity' => $this->getId(),
359 359
 				'property' => $property,
360 360
 				'snaktype' => 'value',
361
-				'value' => \GuzzleHttp\json_encode( [ 'text' => $value, 'language' => $this->lang ] ),
361
+				'value' => \GuzzleHttp\json_encode(['text' => $value, 'language' => $this->lang]),
362 362
 			];
363 363
 		}
364 364
 
365 365
 		// Save the property.
366 366
 		$wdWpOauth = new WdWpOauth();
367
-		$wdWpOauth->makeCall( $setTitleParams, true );
367
+		$wdWpOauth->makeCall($setTitleParams, true);
368 368
 
369 369
 		// Clear the cache.
370
-		$this->cache->deleteItem( $this->getEntityCacheKey( $this->id ) );
370
+		$this->cache->deleteItem($this->getEntityCacheKey($this->id));
371 371
 	}
372 372
 
373 373
 	public function getInstanceOf() {
374
-		$instancesOf = $this->getPropertyOfTypeItem( $this->getId(), self::PROP_INSTANCE_OF );
375
-		return array_shift( $instancesOf );
374
+		$instancesOf = $this->getPropertyOfTypeItem($this->getId(), self::PROP_INSTANCE_OF);
375
+		return array_shift($instancesOf);
376 376
 	}
377 377
 
378 378
 	/**
@@ -385,31 +385,31 @@  discard block
 block discarded – undo
385 385
 
386 386
 	public function getWikipediaIntro() {
387 387
 		$cacheKey = 'wikipedia-intro-' . $this->id . $this->lang;
388
-		if ( $this->cache->hasItem( $cacheKey ) ) {
389
-			return $this->cache->getItem( $cacheKey )->get();
388
+		if ($this->cache->hasItem($cacheKey)) {
389
+			return $this->cache->getItem($cacheKey)->get();
390 390
 		}
391
-		$entity = $this->getEntity( $this->id );
392
-		if ( !isset( $entity['sitelinks'] ) ) {
391
+		$entity = $this->getEntity($this->id);
392
+		if (!isset($entity['sitelinks'])) {
393 393
 			return [];
394 394
 		}
395
-		foreach ( $entity['sitelinks'] as $sitelink ) {
396
-			if ( $sitelink['site'] == $this->lang . 'wiki' ) {
397
-				$api = new MediawikiApi( 'https://' . $this->lang . '.wikipedia.org/w/api.php' );
398
-				$req = new SimpleRequest( 'query', [
395
+		foreach ($entity['sitelinks'] as $sitelink) {
396
+			if ($sitelink['site'] == $this->lang . 'wiki') {
397
+				$api = new MediawikiApi('https://' . $this->lang . '.wikipedia.org/w/api.php');
398
+				$req = new SimpleRequest('query', [
399 399
 					'prop' => 'extracts',
400 400
 					'exintro' => true,
401 401
 					'titles' => $sitelink['title'],
402
-				] );
403
-				$response = $api->getRequest( $req );
404
-				$page = array_shift( $response['query']['pages'] );
402
+				]);
403
+				$response = $api->getRequest($req);
404
+				$page = array_shift($response['query']['pages']);
405 405
 				$out = [
406 406
 					'title' => $page['title'],
407 407
 					'html' => $page['extract'],
408 408
 				];
409
-				$cacheItem = $this->cache->getItem( $cacheKey )
410
-					->expiresAfter( new DateInterval( 'P1D' ) )
411
-					->set( $out );
412
-				$this->cache->save( $cacheItem );
409
+				$cacheItem = $this->cache->getItem($cacheKey)
410
+					->expiresAfter(new DateInterval('P1D'))
411
+					->set($out);
412
+				$this->cache->save($cacheItem);
413 413
 
414 414
 				return $out;
415 415
 			}
@@ -424,22 +424,22 @@  discard block
 block discarded – undo
424 424
 	 * @param bool $ignoreCache
425 425
 	 * @return bool
426 426
 	 */
427
-	public function getEntity( $id = null, $ignoreCache = false ) {
427
+	public function getEntity($id = null, $ignoreCache = false) {
428 428
 		$idActual = $id ?: $this->id;
429
-		$cacheKey = $this->getEntityCacheKey( $idActual );
430
-		if ( !$ignoreCache && $this->cache->hasItem( $cacheKey ) ) {
431
-			return $this->cache->getItem( $cacheKey )->get();
429
+		$cacheKey = $this->getEntityCacheKey($idActual);
430
+		if (!$ignoreCache && $this->cache->hasItem($cacheKey)) {
431
+			return $this->cache->getItem($cacheKey)->get();
432 432
 		}
433
-		$metadataRequest = new SimpleRequest( 'wbgetentities', [ 'ids' => $idActual ] );
434
-		$itemResult = $this->wdApi->getRequest( $metadataRequest );
435
-		if ( !isset( $itemResult['success'] ) || !isset( $itemResult['entities'][$id] ) ) {
433
+		$metadataRequest = new SimpleRequest('wbgetentities', ['ids' => $idActual]);
434
+		$itemResult = $this->wdApi->getRequest($metadataRequest);
435
+		if (!isset($itemResult['success']) || !isset($itemResult['entities'][$id])) {
436 436
 			return false;
437 437
 		}
438 438
 		$metadata = $itemResult['entities'][$idActual];
439
-		$cacheItem = $this->cache->getItem( $cacheKey )
440
-			->expiresAfter( new DateInterval( 'PT10M' ) )
441
-			->set( $metadata );
442
-		$this->cache->save( $cacheItem );
439
+		$cacheItem = $this->cache->getItem($cacheKey)
440
+			->expiresAfter(new DateInterval('PT10M'))
441
+			->set($metadata);
442
+		$this->cache->save($cacheItem);
443 443
 		return $metadata;
444 444
 	}
445 445
 
@@ -448,7 +448,7 @@  discard block
 block discarded – undo
448 448
 	 *
449 449
 	 * @return string
450 450
 	 */
451
-	protected function getEntityCacheKey( $id ) {
451
+	protected function getEntityCacheKey($id) {
452 452
 		return 'entities' . $id;
453 453
 	}
454 454
 }
Please login to merge, or discard this patch.
src/Search.php 2 patches
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -8,44 +8,44 @@
 block discarded – undo
8 8
 
9 9
 class Search {
10 10
 
11
-	/** @var string */
12
-	protected $lang;
11
+    /** @var string */
12
+    protected $lang;
13 13
 
14
-	/** @var CacheItemPoolInterface */
15
-	protected $cache;
14
+    /** @var CacheItemPoolInterface */
15
+    protected $cache;
16 16
 
17
-	/**
18
-	 * Search constructor.
19
-	 * @param string $searchTerm What to search for.
20
-	 * @param string $lang Language to use for the search results.
21
-	 * @param CacheItemPoolInterface $cache The cache to use.
22
-	 */
23
-	public function __construct( $searchTerm, $lang, CacheItemPoolInterface $cache ) {
24
-		$this->searchTerm = $searchTerm;
25
-		$this->lang = $lang;
26
-		$this->cache = $cache;
27
-	}
17
+    /**
18
+     * Search constructor.
19
+     * @param string $searchTerm What to search for.
20
+     * @param string $lang Language to use for the search results.
21
+     * @param CacheItemPoolInterface $cache The cache to use.
22
+     */
23
+    public function __construct( $searchTerm, $lang, CacheItemPoolInterface $cache ) {
24
+        $this->searchTerm = $searchTerm;
25
+        $this->lang = $lang;
26
+        $this->cache = $cache;
27
+    }
28 28
 
29
-	/**
30
-	 * @param string $limit The number of search results to return.
31
-	 * @return Item[]
32
-	 */
33
-	public function getItems( $limit = 'max' ) {
34
-		$api = MediawikiApi::newFromApiEndpoint( 'https://www.wikidata.org/w/api.php' );
35
-		$req = FluentRequest::factory()
36
-			->setAction( 'wbsearchentities' )
37
-			->addParams( [
38
-				'search' => $this->searchTerm,
39
-				'type' => 'item',
40
-				'limit' => $limit,
41
-				'language' => 'en',
42
-			] );
43
-		$results = [];
44
-		$response = $api->getRequest( $req );
45
-		foreach ( $response['search'] as $info ) {
46
-			$item = Item::factory( $info['id'], $this->lang, $this->cache );
47
-			$results[] = $item;
48
-		}
49
-		return $results;
50
-	}
29
+    /**
30
+     * @param string $limit The number of search results to return.
31
+     * @return Item[]
32
+     */
33
+    public function getItems( $limit = 'max' ) {
34
+        $api = MediawikiApi::newFromApiEndpoint( 'https://www.wikidata.org/w/api.php' );
35
+        $req = FluentRequest::factory()
36
+            ->setAction( 'wbsearchentities' )
37
+            ->addParams( [
38
+                'search' => $this->searchTerm,
39
+                'type' => 'item',
40
+                'limit' => $limit,
41
+                'language' => 'en',
42
+            ] );
43
+        $results = [];
44
+        $response = $api->getRequest( $req );
45
+        foreach ( $response['search'] as $info ) {
46
+            $item = Item::factory( $info['id'], $this->lang, $this->cache );
47
+            $results[] = $item;
48
+        }
49
+        return $results;
50
+    }
51 51
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@  discard block
 block discarded – undo
20 20
 	 * @param string $lang Language to use for the search results.
21 21
 	 * @param CacheItemPoolInterface $cache The cache to use.
22 22
 	 */
23
-	public function __construct( $searchTerm, $lang, CacheItemPoolInterface $cache ) {
23
+	public function __construct($searchTerm, $lang, CacheItemPoolInterface $cache) {
24 24
 		$this->searchTerm = $searchTerm;
25 25
 		$this->lang = $lang;
26 26
 		$this->cache = $cache;
@@ -30,20 +30,20 @@  discard block
 block discarded – undo
30 30
 	 * @param string $limit The number of search results to return.
31 31
 	 * @return Item[]
32 32
 	 */
33
-	public function getItems( $limit = 'max' ) {
34
-		$api = MediawikiApi::newFromApiEndpoint( 'https://www.wikidata.org/w/api.php' );
33
+	public function getItems($limit = 'max') {
34
+		$api = MediawikiApi::newFromApiEndpoint('https://www.wikidata.org/w/api.php');
35 35
 		$req = FluentRequest::factory()
36
-			->setAction( 'wbsearchentities' )
37
-			->addParams( [
36
+			->setAction('wbsearchentities')
37
+			->addParams([
38 38
 				'search' => $this->searchTerm,
39 39
 				'type' => 'item',
40 40
 				'limit' => $limit,
41 41
 				'language' => 'en',
42
-			] );
42
+			]);
43 43
 		$results = [];
44
-		$response = $api->getRequest( $req );
45
-		foreach ( $response['search'] as $info ) {
46
-			$item = Item::factory( $info['id'], $this->lang, $this->cache );
44
+		$response = $api->getRequest($req);
45
+		foreach ($response['search'] as $info) {
46
+			$item = Item::factory($info['id'], $this->lang, $this->cache);
47 47
 			$results[] = $item;
48 48
 		}
49 49
 		return $results;
Please login to merge, or discard this patch.
examples/search.php 2 patches
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -9,9 +9,9 @@
 block discarded – undo
9 9
 $search = new \Samwilson\SimpleWikidata\Search( 'pride and prejudice', 'en', $cache );
10 10
 $items = $search->getItems( 3 );
11 11
 foreach ( $items as $item ) {
12
-	$instanceOf = $item->getPropertyOfTypeItem(
13
-		\Samwilson\SimpleWikidata\Item::PROP_INSTANCE_OF
14
-	);
15
-	$instanceOfLabel = isset( $instanceOf[0] ) ? $instanceOf[0]->getItem()->getLabel() : 'UNKNOWN';
16
-	echo $item->getLabel().' ('.$instanceOfLabel.')'."\n";
12
+    $instanceOf = $item->getPropertyOfTypeItem(
13
+        \Samwilson\SimpleWikidata\Item::PROP_INSTANCE_OF
14
+    );
15
+    $instanceOfLabel = isset( $instanceOf[0] ) ? $instanceOf[0]->getItem()->getLabel() : 'UNKNOWN';
16
+    echo $item->getLabel().' ('.$instanceOfLabel.')'."\n";
17 17
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -3,15 +3,15 @@
 block discarded – undo
3 3
 require_once __DIR__ . '/../vendor/autoload.php';
4 4
 
5 5
 // Any PSR6 cache can be used.
6
-$cache = new Stash\Pool( new \Stash\Driver\FileSystem() );
6
+$cache = new Stash\Pool(new \Stash\Driver\FileSystem());
7 7
 
8 8
 // Search for anything.
9
-$search = new \Samwilson\SimpleWikidata\Search( 'pride and prejudice', 'en', $cache );
10
-$items = $search->getItems( 3 );
11
-foreach ( $items as $item ) {
9
+$search = new \Samwilson\SimpleWikidata\Search('pride and prejudice', 'en', $cache);
10
+$items = $search->getItems(3);
11
+foreach ($items as $item) {
12 12
 	$instanceOf = $item->getPropertyOfTypeItem(
13 13
 		\Samwilson\SimpleWikidata\Item::PROP_INSTANCE_OF
14 14
 	);
15
-	$instanceOfLabel = isset( $instanceOf[0] ) ? $instanceOf[0]->getItem()->getLabel() : 'UNKNOWN';
16
-	echo $item->getLabel().' ('.$instanceOfLabel.')'."\n";
15
+	$instanceOfLabel = isset($instanceOf[0]) ? $instanceOf[0]->getItem()->getLabel() : 'UNKNOWN';
16
+	echo $item->getLabel() . ' (' . $instanceOfLabel . ')' . "\n";
17 17
 }
Please login to merge, or discard this patch.