|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace DuckDuckGo; |
| 4 | + |
| 5 | +use DuckDuckGo\Misc; |
| 6 | +use GuzzleHttp\Client as Http; |
| 7 | +use GuzzleHttp\Exception\ClientException; |
| 8 | +use GuzzleHttp\Exception\ServerException; |
| 9 | + |
| 10 | +Class Api |
| 11 | +{ |
| 12 | + /** |
| 13 | + * Api endpoint url. |
| 14 | + * |
| 15 | + * @var string |
| 16 | + */ |
| 17 | + protected $endpoint; |
| 18 | + |
| 19 | + /** |
| 20 | + * DuckDuckGo Api constructor. |
| 21 | + */ |
| 22 | + public function __construct() |
| 23 | + { |
| 24 | + $this->endpoint = "api.duckduckgo.com/"; |
| 25 | + } |
| 26 | + |
| 27 | + /** |
| 28 | + * Perform a query against the DuckDuckGo API. |
| 29 | + * |
| 30 | + * @param string $query |
| 31 | + * @throws Exception |
| 32 | + * @return Json |
| 33 | + */ |
| 34 | + public function zeroClickQuery(string $query) |
| 35 | + { |
| 36 | + $url = $this->buildUrl($query); |
| 37 | + $http = new Http(); |
| 38 | + try { |
| 39 | + $response = $http->request("GET", $url); |
| 40 | + return $response->getBody(); |
| 41 | + } catch (ClientException $e) { |
| 42 | + throw new Exception($e->getResponse()->getBody(), $e->getResponse()->getStatusCode()); |
| 43 | + } catch (ServerException $e) { |
| 44 | + throw new Exception("Could not retrieve API result.", 503); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Build a url with config parameters and query. |
| 50 | + * |
| 51 | + * @param string $query |
| 52 | + * @return string $url |
| 53 | + */ |
| 54 | + public function BuildUrl(string $query) |
| 55 | + { |
| 56 | + $misc = new Misc(); |
| 57 | + |
| 58 | + $parameters = [ |
| 59 | + "q" => urlencode($query), |
| 60 | + "format" => $misc->getConfig("format"), |
| 61 | + "no_html" => $misc->getConfig("html"), |
| 62 | + "no_redirect" => 1, |
| 63 | + "skip_disambig" => $misc->getConfig("disambiguations"), |
| 64 | + ]; |
| 65 | + |
| 66 | + $url = ($misc->getConfig("https")) |
| 67 | + ? "https://".$this->endpoint."?" |
| 68 | + : "https://".$this->endpoint."?"; |
| 69 | + |
| 70 | + $url .= http_build_query($parameters); |
| 71 | + return $url; |
| 72 | + } |
| 73 | +} |
0 commit comments