CurlClient::getRequestHeaders()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Postpay\HttpClients;
4
5
use Postpay\Exceptions\PostpayException;
6
use Postpay\Http\Request;
7
use Postpay\Http\Response;
8
9
class CurlClient implements ClientInterface
10
{
11
    /**
12
     * @var Curl The Curl client.
13
     */
14
    protected $curl;
15
16
    /**
17
     * @param Curl|null The Curl client.
18
     */
19 15
    public function __construct(Curl $curl = null)
20
    {
21 15
        $this->curl = $curl ?: new Curl();
22 15
    }
23
24
    /**
25
     * @inheritdoc
26
     */
27 3
    public function send(Request $request, $timeout = null)
28
    {
29 3
        $headers = [];
30
        $headerCallback = function ($curl, $header_line) use (&$headers) {
31 1
            if (strpos($header_line, ':') === false) {
32 1
                return strlen($header_line);
33
            }
34 1
            list($key, $value) = explode(':', trim($header_line), 2);
35 1
            $headers[trim($key)] = explode(',', trim($value));
36 1
            return strlen($header_line);
37 3
        };
38
        $options = [
39 3
            CURLOPT_CUSTOMREQUEST => $request->getMethod(),
40 3
            CURLOPT_HTTPHEADER => $this->getRequestHeaders($request),
41 3
            CURLOPT_URL => $request->getUrl(),
42 3
            CURLOPT_USERPWD => implode(':', $request->getAuth()),
43 3
            CURLOPT_RETURNTRANSFER => true,
44 3
            CURLOPT_CONNECTTIMEOUT => 10,
45 3
            CURLOPT_TIMEOUT => $timeout,
46 3
            CURLOPT_HEADERFUNCTION => $headerCallback,
47
        ];
48 3
        if ($request->getMethod() !== 'GET') {
49 1
            $options[CURLOPT_POSTFIELDS] = json_encode($request->json());
50
        }
51 3
        $this->curl->setOptArray($options);
52 3
        $raw = $this->curl->execute();
53 3
        $statusCode = $this->curl->getInfo(CURLINFO_HTTP_CODE);
54
55 3
        if ($errorCode = $this->curl->errno()) {
56 1
            throw new PostpayException($this->curl->error(), $errorCode);
57
        }
58 2
        $this->curl->close();
59 2
        return new Response($request, $statusCode, $headers, $raw);
60
    }
61
62
    /**
63
     * Get request headers.
64
     *
65
     * @param Request $request
66
     *
67
     * @return array
68
     */
69 4
    public function getRequestHeaders(Request $request)
70
    {
71 4
        $headers = [];
72 4
        foreach ($request->getHeaders() as $key => $value) {
73 3
            $headers[] = $key . ': ' . $value;
74
        }
75 4
        return $headers;
76
    }
77
}
78