ApiEntityIdForTermLookup::doResultsMatch()   B
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
ccs 8
cts 8
cp 1
rs 8.8571
cc 5
eloc 6
nc 5
nop 2
crap 5
1
<?php
2
3
namespace Wikibase\EntityStore\Api;
4
5
use Mediawiki\Api\MediawikiApi;
6
use Mediawiki\Api\SimpleRequest;
7
use Wikibase\DataModel\Entity\EntityIdParser;
8
use Wikibase\DataModel\Term\Term;
9
use Wikibase\EntityStore\Internal\EntityIdForTermLookup;
10
11
/**
12
 * Internal class
13
 *
14
 * @licence GPLv2+
15
 * @author Thomas Pellissier Tanon
16
 * @todo removes limit of 50 results?
17
 */
18
class ApiEntityIdForTermLookup implements EntityIdForTermLookup {
19
20
	/**
21
	 * @var MediawikiApi
22
	 */
23
	private $api;
24
25
	/**
26
	 * @var EntityIdParser
27
	 */
28
	private $entityIdParser;
29
30
	/**
31
	 * @param MediaWikiApi $api
32
	 * @param EntityIdParser $entityIdParser
33
	 */
34 2
	public function __construct( MediaWikiApi $api, EntityIdParser $entityIdParser ) {
35 2
		$this->api = $api;
36 2
		$this->entityIdParser = $entityIdParser;
37 2
	}
38
39
	/**
40
	 * @see EntityIdsForTermLookup::getEntityIdsForTerm
41
	 */
42 2
	public function getEntityIdsForTerm( Term $term, $entityType ) {
43 2
		return $this->parseResult( $this->api->getRequest( $this->buildRequest( $term, $entityType ) ), $term->getText() );
44
	}
45
46 2
	protected function buildRequest( Term $term, $entityType ) {
47 2
		return new SimpleRequest(
48 2
			'wbsearchentities',
49
			[
50 2
				'search' => $term->getText(),
51 2
				'language' => $term->getLanguageCode(),
52 2
				'type' => $entityType,
53
				'limit' => 50
54 2
			]
55 2
		);
56
	}
57
58 2
	private function parseResult( array $result, $search ) {
59 2
		$search = $this->cleanLabel( $search );
60
61 2
		$results = $this->filterResults( $result['search'], $search );
62
63 2
		$entityIds = [];
64 2
		foreach( $results as $entry ) {
65 2
			$entityIds[] = $this->entityIdParser->parse( $entry['id'] );
66 2
		}
67
68 2
		return $entityIds;
69
	}
70
71 2
	private function filterResults( array $results, $search ) {
72 2
		$filtered = [];
73 2
		foreach( $results as $entry ) {
74 2
			if( $this->doResultsMatch($entry, $search ) ) {
75 2
				$filtered[] = $entry;
76 2
			}
77 2
		}
78
79 2
		return $filtered;
80
	}
81
82 2
	private function doResultsMatch( array $entry, $search ) {
83 2
		if( array_key_exists( 'aliases', $entry ) ) {
84 1
			foreach( $entry['aliases'] as $alias ) {
85 1
				if( $this->cleanLabel( $alias ) === $search ) {
86 1
					return true;
87
				}
88 1
			}
89 1
		}
90
91 2
		return array_key_exists( 'label', $entry ) && $this->cleanLabel($entry['label']) === $search;
92
	}
93
94 2
	private function cleanLabel($label) {
95 2
		$label = mb_strtolower( $label, 'UTF-8' );
96 2
		return trim( $label );
97
	}
98
}
99