Passed
Push — master ( b6a873...a57dbe )
by Radosław
02:08
created

Bing::searchRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 1

Importance

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