Completed
Push — master ( 951284...b5c57e )
by
unknown
06:36 queued 11s
created

includes/Formatters/EntityIdSiteLinkFormatter.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Wikibase\Lib\Formatters;
4
5
use Wikibase\DataModel\Entity\EntityId;
6
use Wikibase\DataModel\Entity\ItemId;
7
use Wikibase\DataModel\Services\EntityId\EntityIdFormatter;
8
use Wikibase\DataModel\Services\Lookup\LabelDescriptionLookup;
9
use Wikibase\DataModel\Services\Lookup\LabelDescriptionLookupException;
10
use Wikibase\Lib\Store\EntityTitleLookup;
11
12
/**
13
 * A formatter for exclusive use on client wikis. It expects an entity ID and returns a wikitext
14
 * snippet, containing a link to a local page as specified by the relevant sitelink, labeled with
15
 * the label in the local (or a fallback) language. Both the sitelink and the label are optional.
16
 *
17
 * @license GPL-2.0-or-later
18
 * @author Thiemo Kreuz
19
 */
20
class EntityIdSiteLinkFormatter implements EntityIdFormatter {
21
22
	/**
23
	 * @var EntityTitleLookup
24
	 */
25
	private $entityTitleLookup;
26
27
	/**
28
	 * @var LabelDescriptionLookup
29
	 */
30
	private $labelLookup;
31
32
	public function __construct(
33
		EntityTitleLookup $entityTitleLookup,
34
		LabelDescriptionLookup $labelLookup
35
	) {
36
		$this->entityTitleLookup = $entityTitleLookup;
37
		$this->labelLookup = $labelLookup;
38
	}
39
40
	/**
41
	 * @see EntityIdFormatter::formatEntityId
42
	 *
43
	 * @param EntityId $entityId
44
	 *
45
	 * @return string Wikitext
46
	 */
47
	public function formatEntityId( EntityId $entityId ) {
48
		$term = null;
49
50
		try {
51
			$term = $this->labelLookup->getLabel( $entityId );
52
		} catch ( LabelDescriptionLookupException $ex ) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
53
		}
54
55
		// TODO: Add language fallback indicator
56
		$label = $term ? wfEscapeWikiText( $term->getText() ) : '';
57
58
		if ( $entityId instanceof ItemId ) {
59
			$title = $this->entityTitleLookup->getTitleForId( $entityId );
60
61
			if ( $title !== null ) {
62
				$pageName = $title->getFullText();
63
				$optionalLabel = $label === '' ? '' : '|' . $label;
64
65
				return '[[' . $pageName . $optionalLabel . ']]';
66
			}
67
		}
68
69
		return $label === '' ? $entityId->getSerialization() : $label;
70
	}
71
72
}
73