UnitSymbolFormatter::format()   B
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 22
ccs 12
cts 12
cp 1
rs 8.6737
c 1
b 0
f 0
cc 5
eloc 15
nc 5
nop 1
crap 5
1
<?php
2
3
namespace PPP\Wikidata\ValueFormatters\JsonLd\Entity;
4
5
use OutOfBoundsException;
6
use ValueFormatters\FormatterOptions;
7
use ValueFormatters\FormattingException;
8
use ValueFormatters\ValueFormatter;
9
use ValueFormatters\ValueFormatterBase;
10
use Wikibase\DataModel\Entity\EntityIdParser;
11
use Wikibase\DataModel\Entity\EntityIdParsingException;
12
use Wikibase\DataModel\Services\Lookup\ItemLookup;
13
14
/**
15
 * @licence AGPLv3+
16
 * @author Thomas Pellissier Tanon
17
 */
18
class UnitSymbolFormatter extends ValueFormatterBase {
19
20
	/**
21
	 * @var EntityIdParser
22
	 */
23
	private $entityIriParser;
24
25
	/**
26
	 * @var EntityOntology
27
	 */
28
	private $entityOntology;
29
30
	/**
31
	 * @var ItemLookup
32
	 */
33
	private $itemLookup;
34
35 3
	public function __construct(
36
		EntityIdParser $entityIriParser,
37
		EntityOntology $entityOntology,
38
		ItemLookup $itemLookup,
39
		FormatterOptions $options = null
40
	) {
41 3
		$this->entityIriParser = $entityIriParser;
42 3
		$this->entityOntology = $entityOntology;
43 3
		$this->itemLookup = $itemLookup;
44
45 3
		parent::__construct($options);
46 3
	}
47
48
	/**
49
	 * @see ValueFormatterBase::format
50
	 */
51 5
	public function format($value) {
52
		try {
53 5
			$itemId = $this->entityIriParser->parse($value);
54 5
		} catch(EntityIdParsingException $e) {
55 1
			throw new FormattingException('Invalid unit IRI: ' . $value);
56
		}
57
58 4
		$item = $this->itemLookup->getItemForId($itemId);
0 ignored issues
show
Compatibility introduced by
$itemId of type object<Wikibase\DataModel\Entity\EntityId> is not a sub-type of object<Wikibase\DataModel\Entity\ItemId>. It seems like you assume a child class of the class Wikibase\DataModel\Entity\EntityId to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
59 4
		if($item === null) {
60 1
			throw new FormattingException('Item not found: ' . $value);
61
		}
62
63
		try {
64 3
			return $this->entityOntology->getUnitSymbol($item);
65 2
		} catch(OutOfBoundsException $e) {
66
			try {
67 2
				return $item->getFingerprint()->getLabel($this->getOption(ValueFormatter::OPT_LANG))->getText();
68 1
			} catch (OutOfBoundsException $e) {
69 1
				throw new FormattingException('No unit symbol and no label for IRI ' . $value);
70
			}
71
		}
72
	}
73
}
74