Search::getItems()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 14
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 17
ccs 0
cts 17
cp 0
crap 6
rs 9.7998
1
<?php
2
3
namespace Samwilson\SimpleWikidata;
4
5
use Mediawiki\Api\FluentRequest;
6
use Mediawiki\Api\MediawikiApi;
7
use Psr\Cache\CacheItemPoolInterface;
8
9
class Search {
10
11
	/** @var string */
12
	protected $lang;
13
14
	/** @var CacheItemPoolInterface */
15
	protected $cache;
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;
0 ignored issues
show
Bug Best Practice introduced by
The property searchTerm does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
25
		$this->lang = $lang;
26
		$this->cache = $cache;
27
	}
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
	}
51
}
52