Completed
Push — master ( f920cb...5251c6 )
by Maik
01:19
created

JsonProvider::provideUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
namespace Nkey\DDG\API;
3
4
use Generics\Client\HttpClient;
5
use Generics\Socket\Url;
6
7
/**
8
 * This class provides means of fetching data from duckduckgo api
9
 *
10
 * @author Maik Greubel <[email protected]>
11
 * @license Apache 2.0
12
 */
13
class JsonProvider
14
{
15
16
    /**
17
     *
18
     * @var HttpClient
19
     */
20
    private $httpClient;
21
22
    /**
23
     * Query the duck duck go api
24
     *
25
     * @param string $query
26
     *            Keywords to start a query for
27
     * @return string The payload
28
     */
29 2
    public function query(string $query): string
30
    {
31 2
        $this->httpClient = new HttpClient($this->provideUrl($query));
32 2
        $this->httpClient->setHeader('User-Agent', '*');
33 2
        $this->httpClient->setHeader('Accept-Encoding', 'identity'); // Currently there is a bug in HttpClient for passing buf to gzdecode()
34 2
        $this->httpClient->request('GET');
35 2
        $response = "";
36
        
37 2
        while ($this->httpClient->getPayload()->ready()) {
38 2
            $response .= $this->httpClient->getPayload()->read($this->httpClient->getPayload()
39 2
                ->count());
40
        }
41
        
42 2
        return $response;
43
    }
44
    
45
    /**
46
     * Provide an URL object out of given duckduckgo query
47
     * @param string $query
48
     * @return Url
49
     */
50 2
    private function provideUrl(string $query): Url
51
    {
52 2
        $url = new Url(sprintf("http://api.duckduckgo.com/?q=%s&format=json", urlencode($query)));
53
        
54 2
        return $url;
55
    }
56
}
57