1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace wlbrough\clearbit\Abstracts; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Client; |
6
|
|
|
use wlbrough\clearbit\Exceptions\ApiException; |
7
|
|
|
|
8
|
|
|
abstract class Api |
9
|
|
|
{ |
10
|
|
|
protected $endpointUrl = null; |
11
|
|
|
protected $useStreaming = false; |
12
|
|
|
|
13
|
27 |
|
public function setWebhookEndpoint($endpointUrl = null) |
14
|
|
|
{ |
15
|
27 |
|
self::validateUrl($endpointUrl); |
16
|
12 |
|
$this->endpointUrl = $endpointUrl; |
17
|
12 |
|
} |
18
|
|
|
|
19
|
3 |
|
public function enableStreaming() |
20
|
|
|
{ |
21
|
3 |
|
$this->useStreaming = true; |
22
|
3 |
|
} |
23
|
|
|
|
24
|
27 |
|
private static function validateUrl($url) |
25
|
|
|
{ |
26
|
27 |
|
if (!is_string($url)) { |
27
|
9 |
|
throw new \InvalidArgumentException('Webhook endpoint is not a string'); |
28
|
|
|
} |
29
|
|
|
|
30
|
18 |
|
$isValid = preg_match('#((https?|ftp)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i', $url); |
31
|
|
|
|
32
|
18 |
|
if (!$isValid) { |
33
|
6 |
|
throw new \InvalidArgumentException('Webhook endpoint is not a URL'); |
34
|
|
|
} |
35
|
|
|
|
36
|
12 |
|
return true; |
37
|
|
|
} |
38
|
|
|
|
39
|
18 |
|
protected static function call($url, $client) |
40
|
|
|
{ |
41
|
18 |
|
if (!$client) { |
42
|
|
|
$client = new Client(['http_errors' => false]); |
43
|
|
|
} |
44
|
|
|
|
45
|
18 |
|
$response = $client->get($url); |
46
|
18 |
|
$status = $response->getStatusCode(); |
47
|
|
|
|
48
|
18 |
|
if ($status === 200) { |
49
|
9 |
|
$returnData = json_decode($response->getBody()); |
50
|
3 |
|
} else { |
51
|
9 |
|
throw new ApiException($status); |
52
|
|
|
} |
53
|
|
|
|
54
|
9 |
|
return $returnData; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
protected static function post($url, $body, $successCode = 200, $client = null) |
58
|
|
|
{ |
59
|
|
|
if (!$client) { |
60
|
|
|
$client = new Client(['http_errors' => false]); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
$response = $client->post($url, [ |
64
|
|
|
'form_params' => $body |
65
|
|
|
]); |
66
|
|
|
$status = $response->getStatusCode(); |
67
|
|
|
|
68
|
|
|
return $status === $successCode; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|