CurlTransport::get()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 23
rs 9.8333
cc 3
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Kosv\RandomUser\Transport;
6
7
use Kosv\RandomUser\Exceptions\TransportRequestException;
8
use Kosv\RandomUser\Interfaces\TransportResponseInterface;
9
use Kosv\RandomUser\Interfaces\TransportInterface;
10
11
final class CurlTransport implements TransportInterface
12
{
13
    private const DEFAULT_CONNECTION_TIMEOUT = 30;
14
15
    private int $connectionTimeout;
16
17
    public function __construct(int $connectionTimeout = self::DEFAULT_CONNECTION_TIMEOUT)
18
    {
19
        $this->connectionTimeout = $connectionTimeout;
20
    }
21
22
    /**
23
     * @throws TransportRequestException
24
     */
25
    public function get(string $url): TransportResponseInterface
26
    {
27
        $ch = curl_init();
28
29
        curl_setopt_array($ch, [
30
            CURLOPT_CONNECTTIMEOUT => $this->connectionTimeout,
31
            CURLOPT_RETURNTRANSFER => true,
32
            CURLOPT_URL => $url,
33
        ]);
34
35
        $result = curl_exec($ch);
36
37
        $chErrCode = curl_errno($ch);
38
        $chErr = curl_error($ch);
39
40
        $statusCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
41
        curl_close($ch);
42
43
        if ($chErrCode || $chErr) {
44
            throw new TransportRequestException(sprintf('Error while executing request in curl transport. Error: "%s".', $chErr));
45
        }
46
47
        return new Response($statusCode, (string)$result);
48
    }
49
}
50