Passed
Push — master ( 20bdbe...2f8437 )
by Radosław
03:08
created

Bing::validateResult()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
ccs 4
cts 4
cp 1
rs 9.4285
cc 3
eloc 3
nc 2
nop 1
crap 3
1
<?php
2
3
namespace Radowoj\Searcher\SearchProvider;
4
5
use stdClass;
6
use InvalidArgumentException;
7
8
use GuzzleHttp\Client as GuzzleClient;
9
10
use Radowoj\Searcher\SearchResult\Collection;
11
use Radowoj\Searcher\SearchResult\Item;
12
13
14
class Bing extends SearchProvider implements ISearchProvider
15
{
16
    const URI = 'https://api.cognitive.microsoft.com/bing/v5.0/search?';
17
    const API_KEY_HEADER = 'Ocp-Apim-Subscription-Key';
18
19
    protected $apiKey = null;
20
21
    protected $guzzle = null;
22
23 4
    public function __construct(string $apiKey, GuzzleClient $guzzle)
24
    {
25 4
        $this->apiKey = $apiKey;
26 4
        $this->guzzle = $guzzle;
27 4
    }
28
29
30 4
    protected function searchRequest(string $query, int $limit, int $offset) : stdClass
31
    {
32
        $params = [
33 4
            'q' => $query,
34 4
            'count' => $limit,
35 4
            'offset' => $offset
36
        ];
37
38 4
        $queryString = http_build_query($params);
39
40 4
        $uri = self::URI . $queryString;
41
42 4
        $result = $this->guzzle->request(
43 4
            'GET',
44
            $uri, [
45
                'headers' => [
46 4
                    self::API_KEY_HEADER => $this->apiKey
47
                ]
48
            ]
49
        );
50
51 4
        return json_decode($result->getBody());
52
    }
53
54
55 4
    protected function validateResult(stdClass $result)
56
    {
57 4
        if (!isset($result->webPages->value) || !isset($result->webPages->totalEstimatedMatches)) {
58 1
            throw new InvalidArgumentException("Invalid Bing API response: " . print_r($result, 1));
59
        }
60 3
    }
61
62
63 4
    protected function getCollection(stdClass $result)
64
    {
65 4
        $this->validateResult($result);
66
67 3
        $results = array_map(function($item) {
68
            return new Item([
69
                'url' => $item->displayUrl,
70
                'title' => $item->name,
71
                'description' => $item->snippet,
72
            ]);
73 3
        }, $result->webPages->value);
74
75 3
        return new Collection(
76
            $results,
77 3
            $result->webPages->totalEstimatedMatches
78
        );
79
    }
80
81
82
}
83