1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Inspirum\Balikobot\Client; |
6
|
|
|
|
7
|
|
|
use GuzzleHttp\Psr7\Response; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
use RuntimeException; |
10
|
|
|
use function base64_encode; |
11
|
|
|
use function count; |
12
|
|
|
use function curl_close; |
13
|
|
|
use function curl_errno; |
14
|
|
|
use function curl_error; |
15
|
|
|
use function curl_exec; |
16
|
|
|
use function curl_getinfo; |
17
|
|
|
use function curl_init; |
18
|
|
|
use function curl_setopt; |
19
|
|
|
use function json_encode; |
20
|
|
|
use function sprintf; |
21
|
|
|
use const CURLINFO_HTTP_CODE; |
22
|
|
|
use const CURLOPT_HEADER; |
23
|
|
|
use const CURLOPT_HTTPHEADER; |
24
|
|
|
use const CURLOPT_POST; |
25
|
|
|
use const CURLOPT_POSTFIELDS; |
26
|
|
|
use const CURLOPT_RETURNTRANSFER; |
27
|
|
|
use const CURLOPT_SSL_VERIFYHOST; |
28
|
|
|
use const CURLOPT_SSL_VERIFYPEER; |
29
|
|
|
use const CURLOPT_URL; |
30
|
|
|
|
31
|
|
|
final class DefaultCurlRequester implements Requester |
32
|
|
|
{ |
33
|
544 |
|
public function __construct( |
34
|
|
|
private readonly string $apiUser, |
35
|
|
|
private readonly string $apiKey, |
36
|
|
|
private readonly bool $sslVerify = true, |
37
|
|
|
) { |
38
|
544 |
|
} |
39
|
|
|
|
40
|
|
|
/** @inheritDoc */ |
41
|
544 |
|
public function request(string $url, array $data = []): ResponseInterface |
42
|
|
|
{ |
43
|
|
|
// init curl |
44
|
544 |
|
$ch = curl_init(); |
45
|
|
|
|
46
|
|
|
// set headers |
47
|
544 |
|
curl_setopt($ch, CURLOPT_URL, $url); |
48
|
544 |
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
49
|
544 |
|
curl_setopt($ch, CURLOPT_HEADER, false); |
50
|
|
|
|
51
|
|
|
// disable SSL verification |
52
|
544 |
|
if ($this->sslVerify === false) { |
53
|
1 |
|
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); |
54
|
1 |
|
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
// set data |
58
|
544 |
|
if (count($data) > 0) { |
59
|
31 |
|
curl_setopt($ch, CURLOPT_POST, true); |
60
|
31 |
|
curl_setopt($ch, CURLOPT_POSTFIELDS, (string) json_encode($data)); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
// set auth |
64
|
544 |
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [ |
65
|
544 |
|
sprintf('Authorization: Basic %s', base64_encode(sprintf('%s:%s', $this->apiUser, $this->apiKey))), |
66
|
544 |
|
'Content-Type: application/json', |
67
|
544 |
|
]); |
68
|
|
|
|
69
|
|
|
// execute curl |
70
|
544 |
|
$response = curl_exec($ch); |
71
|
544 |
|
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); |
72
|
|
|
|
73
|
|
|
// check for errors. |
74
|
544 |
|
if ($response === false) { |
75
|
1 |
|
throw new RuntimeException(curl_error($ch), curl_errno($ch)); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
// close curl |
79
|
543 |
|
curl_close($ch); |
80
|
|
|
|
81
|
543 |
|
return new Response((int) $statusCode, [], (string) $response); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|