summaryrefslogtreecommitdiffstats
path: root/vendor/gipfl/curl/src/CurlHandle.php
blob: d5309f08d8f7a1b3c90e1ef5f292c73eb0dfd812 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php

namespace gipfl\Curl;

use Psr\Http\Message\RequestInterface;

class CurlHandle
{
    protected static $curlOptions = [
        CURLOPT_HEADER         => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_ENCODING       => 'gzip',
        CURLOPT_TCP_NODELAY    => true,
        CURLINFO_HEADER_OUT    => true,
        CURLOPT_TCP_KEEPALIVE  => 1,
        CURLOPT_BUFFERSIZE     => 512 * 1024,
    ];

    public static function createForRequest(RequestInterface $request, $curlOptions = [])
    {
        $headers = [];
        foreach ($request->getHeaders() as $name => $values) {
            foreach ($values as $value) {
                $headers[] = "$name: $value";
            }
        }
        $body = $request->getBody();
        if ($body->getSize() > 0) {
            $body = $body->getContents();
        } else {
            $body = null;
        }


        $curl = curl_init();
        $opts = static::prepareCurlOptions(
            $request->getMethod(),
            (string) $request->getUri(),
            $body,
            $headers,
            $curlOptions
        );
        curl_setopt_array($curl, $opts);

        return $curl;
    }

    protected static function prepareCurlOptions($method, $url, $body = null, $headers = [], $curlOptions = [])
    {
        $opts = $curlOptions + [
                CURLOPT_CUSTOMREQUEST  => $method,
                CURLOPT_URL            => $url,
            ] + self::$curlOptions;

        if (isset($opts[CURLOPT_HTTPHEADER])) {
            $opts[CURLOPT_HTTPHEADER] = array_merge($opts[CURLOPT_HTTPHEADER], $headers);
        } else {
            $opts[CURLOPT_HTTPHEADER] = $headers;
        }
        if (isset($opts[CURLOPT_PROXYTYPE])
            && $opts[CURLOPT_PROXYTYPE] === CURLPROXY_HTTP
            && defined('CURLOPT_SUPPRESS_CONNECT_HEADERS')
        ) {
            $opts[CURLOPT_SUPPRESS_CONNECT_HEADERS] = true;
        }

        if ($body !== null) {
            $opts[CURLOPT_POSTFIELDS] = $body;
        }

        return $opts;
    }
}