|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Messerli90\Hunterio; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Http\Client\Response; |
|
6
|
|
|
use Illuminate\Support\Facades\Http; |
|
7
|
|
|
use Messerli90\Hunterio\Exceptions\AuthorizationException; |
|
8
|
|
|
use Messerli90\Hunterio\Exceptions\InvalidRequestException; |
|
9
|
|
|
use Messerli90\Hunterio\Exceptions\UsageException; |
|
10
|
|
|
use Messerli90\Hunterio\Interfaces\EndpointInterface; |
|
11
|
|
|
|
|
12
|
|
|
class HunterClient implements EndpointInterface |
|
13
|
|
|
{ |
|
14
|
|
|
/** @var string */ |
|
15
|
|
|
protected $api_key; |
|
16
|
|
|
|
|
17
|
|
|
/** @var string */ |
|
18
|
|
|
protected $base_url = "https://api.hunter.io/v2"; |
|
19
|
|
|
|
|
20
|
|
|
/** @var string */ |
|
21
|
|
|
public $endpoint = ""; |
|
22
|
|
|
|
|
23
|
|
|
/** @var array */ |
|
24
|
|
|
public $query_params = []; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* @param string|null $api_key |
|
28
|
|
|
* @throws AuthorizationException |
|
29
|
|
|
*/ |
|
30
|
|
|
public function __construct(string $api_key = null) |
|
31
|
|
|
{ |
|
32
|
|
|
if (empty($api_key)) { |
|
33
|
|
|
throw new AuthorizationException('API key required'); |
|
34
|
|
|
} |
|
35
|
|
|
$this->api_key = $api_key; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* |
|
40
|
|
|
* @param mixed $attr |
|
41
|
|
|
* @return mixed |
|
42
|
|
|
*/ |
|
43
|
|
|
public function __get($attr) |
|
44
|
|
|
{ |
|
45
|
|
|
return $this->$attr; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
public function make() |
|
49
|
|
|
{ |
|
50
|
|
|
return array_filter($this->query_params, function ($q) { |
|
51
|
|
|
return isset($q); |
|
52
|
|
|
}); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
protected function buildUrl() |
|
56
|
|
|
{ |
|
57
|
|
|
return "{$this->base_url}/{$this->endpoint}"; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
public function get() |
|
61
|
|
|
{ |
|
62
|
|
|
$response = Http::get($this->buildUrl(), $this->make()); |
|
63
|
|
|
|
|
64
|
|
|
if ($response->ok()) { |
|
65
|
|
|
return $response->json(); |
|
66
|
|
|
} else { |
|
67
|
|
|
return $this->handleErrors($response); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
protected function handleErrors(Response $response) |
|
72
|
|
|
{ |
|
73
|
|
|
$message = $response->json()['errors'][0]['details']; |
|
74
|
|
|
if ($response->status() === 401) { |
|
75
|
|
|
// No valid API key was provided. |
|
76
|
|
|
throw new AuthorizationException($message); |
|
77
|
|
|
} else if (in_array($response->status(), [403, 429])) { |
|
78
|
|
|
// Thrown when `usage limit` or `rate limit` is reached |
|
79
|
|
|
// Upgrade your plan if necessary. |
|
80
|
|
|
throw new UsageException($message); |
|
81
|
|
|
} else { |
|
82
|
|
|
// Your request was not valid. |
|
83
|
|
|
throw new InvalidRequestException($message); |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|