1 | <?php |
||
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 ) { |
|
38 | |||
39 | /** |
||
40 | * @see EntityIdsForTermLookup::getEntityIdsForTerm |
||
41 | */ |
||
42 | 2 | public function getEntityIdsForTerm( Term $term, $entityType ) { |
|
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) { |
|
98 | } |
||
99 |