DefaultCurlRequester   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 19
c 0
b 0
f 0
dl 0
loc 51
ccs 23
cts 23
cp 1
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A request() 0 41 4
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