-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathClient.php
103 lines (88 loc) · 2.69 KB
/
Client.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
namespace Twingly;
require 'vendor/autoload.php';
/**
* Twingly Search API client
*
* @package Twingly
*/
class Client {
const VERSION = '2.1.1';
const BASE_URL = 'https://api.twingly.com';
const SEARCH_API_VERSION = 'v3';
const SEARCH_PATH = '/blog/search/api/'. self::SEARCH_API_VERSION .'/search';
const DEFAULT_USER_AGENT = 'Twingly Search PHP Client/%s';
public $api_key = null;
public $user_agent = null;
public $guzzle;
/**
* Client constructor.
*
* @param string $api_key Twingly Search API Key. If not provided, reads key from environment (TWINGLY_SEARCH_KEY)
* @param string $user_agent User Agent for client
*
* @throws AuthException if no API key was provided
*/
function __construct($api_key = false, $user_agent = false)
{
if(!$api_key) {
$api_key = $this->env_api_key();
}
if(!$api_key) {
$this->api_key_missing();
}
$this->api_key = $api_key;
if(!$user_agent) {
$user_agent = sprintf(Client::DEFAULT_USER_AGENT, Client::VERSION);
}
$this->user_agent = $user_agent;
$this->guzzle = new \GuzzleHttp\Client([
'base_uri' => Client::BASE_URL,
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'User-Agent' => $this->user_agent,
'Accept-Encoding' => 'gzip'
],
'verify' => false
]);
}
/**
* Returns a new Query object connected to this client
*
* @return Query
*/
public function query() {
return new Query($this);
}
/**
* Executes the given Query and returns the result
*
* This method should not be called manually, instead use Query->execute().
*
* @param Query $query the query to be executed
*
* @return Result
*/
public function execute_query($query) {
$response_body = $this->get_response($query)->getBody();
$parser = new Parser();
return $parser->parse($response_body);
}
/**
* @return string API endpoint URL
*/
public function endpoint_url() {
return sprintf('%s%s', Client::BASE_URL, Client::SEARCH_PATH);
}
private function env_api_key() {
return getenv('TWINGLY_SEARCH_KEY');
}
private function get_response($query) {
$response = $this->guzzle->get($query->url(), ['http_errors' => false]); // disable http errors, we will handle them
return $response;
}
private function api_key_missing() {
throw new AuthException('No API key has been provided.');
}
}