CurlTransport   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 17
c 1
b 0
f 0
dl 0
loc 37
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A get() 0 23 3
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