Passed
Push — master ( 12bba4...f7937a )
by Shahrad
01:31
created

Middleware::handle_media()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
c 0
b 0
f 0
dl 0
loc 20
rs 9.5222
cc 5
nc 7
nop 2
1
<?php
2
3
namespace EasyHttp;
4
5
use EasyHttp\Model\HttpOptions;
6
use EasyHttp\Util\Utils;
7
8
/**
9
 * Class Middleware
10
 *
11
 * @link    https://github.com/shahradelahi/easy-http
12
 * @author  Shahrad Elahi (https://github.com/shahradelahi)
13
 * @license https://github.com/shahradelahi/easy-http/blob/master/LICENSE (MIT License)
14
 */
15
class Middleware
16
{
17
18
    /**
19
     * Create curl handler.
20
     *
21
     * @param ?string $method
22
     * @param string $uri
23
     * @param array|HttpOptions $options
24
     *
25
     * @return false|\CurlHandle
26
     */
27
    public static function create_curl_handler(?string $method, string $uri, array|HttpOptions $options = []): false|\CurlHandle
28
    {
29
        $handler = curl_init();
30
        if (is_resource($handler) || !$handler) {
31
            return false;
32
        }
33
34
        if (gettype($options) === 'array') {
35
            $options = new HttpOptions($options);
36
        }
37
38
        if (count($options->getQuery()) > 0) {
39
            if (!str_contains($uri, '?')) {
40
                $uri .= '?';
41
            }
42
            $uri .= $options->getQueryString();
43
        }
44
45
        curl_setopt($handler, CURLOPT_URL, $uri);
46
47
        self::set_curl_options($handler, $method, $options);
48
49
        return $handler;
50
    }
51
52
    /**
53
     * Setup curl options based on the given method and our options.
54
     *
55
     * @param \CurlHandle $cHandler
56
     * @param ?string $method
57
     * @param HttpOptions $options
58
     *
59
     * @return void
60
     */
61
    public static function set_curl_options(\CurlHandle $cHandler, ?string $method, HttpOptions $options): void
62
    {
63
        curl_setopt($cHandler, CURLOPT_HEADER, true);
64
        curl_setopt($cHandler, CURLOPT_CUSTOMREQUEST, $method ?? 'GET');
65
66
        # Fetch the header
67
        $fetchedHeaders = [];
68
        foreach ($options->getHeader() as $header => $value) {
69
            $fetchedHeaders[] = $header . ': ' . $value;
70
        }
71
72
        # Set headers
73
        curl_setopt($cHandler, CURLOPT_HTTPHEADER, $fetchedHeaders ?? []);
74
75
76
        # Add body if we have one.
77
        if ($options->getBody()) {
78
            curl_setopt($cHandler, CURLOPT_CUSTOMREQUEST, $method ?? 'POST');
79
            curl_setopt($cHandler, CURLOPT_POSTFIELDS, $options->getBody());
80
            curl_setopt($cHandler, CURLOPT_POST, true);
81
        }
82
83
        # Check for a proxy
84
        if ($options->getProxy() != null) {
85
            curl_setopt($cHandler, CURLOPT_PROXY, $options->getProxy()->getHost());
86
            curl_setopt($cHandler, CURLOPT_PROXYUSERPWD, $options->getProxy()->getAuth());
87
            if ($options->getProxy()->type !== null) {
88
                curl_setopt($cHandler, CURLOPT_PROXYTYPE, $options->getProxy()->type);
89
            }
90
        }
91
92
        curl_setopt($cHandler, CURLOPT_RETURNTRANSFER, true);
93
        curl_setopt($cHandler, CURLOPT_FOLLOWLOCATION, true);
94
95
        # Add and override the custom curl options.
96
        foreach ($options->getCurlOptions() as $option => $value) {
97
            curl_setopt($cHandler, $option, $value);
98
        }
99
100
        # if we have a timeout, set it.
101
        curl_setopt($cHandler, CURLOPT_TIMEOUT, $options->getTimeout());
102
103
        # If self-signed certs are allowed, set it.
104
        if ((bool)getenv('HAS_SELF_SIGNED_CERT') === true) {
105
            curl_setopt($cHandler, CURLOPT_SSL_VERIFYPEER, false);
106
            curl_setopt($cHandler, CURLOPT_SSL_VERIFYHOST, false);
107
        }
108
109
        (new Middleware())->handle_media($cHandler, $options);
110
    }
111
112
    /**
113
     * Handle the media
114
     *
115
     * @param \CurlHandle $handler
116
     * @param HttpOptions $options
117
     * @return void
118
     */
119
    private function handle_media(\CurlHandle $handler, HttpOptions $options): void
120
    {
121
        if (count($options->getMultipart()) > 0) {
122
            curl_setopt($handler, CURLOPT_POST, true);
123
            curl_setopt($handler, CURLOPT_CUSTOMREQUEST, 'POST');
124
125
            $form_data = new FormData();
126
            foreach ($options->getMultipart() as $key => $value) {
127
                $form_data->addFile($key, $value);
128
            }
129
130
            $headers = [];
131
            foreach ($options->getHeader() as $header => $value) {
132
                if (Utils::insensitiveString($header, 'content-type')) continue;
133
                $headers[] = $header . ': ' . $value;
134
            }
135
            $headers[] = 'Content-Type: multipart/form-data';
136
137
            curl_setopt($handler, CURLOPT_HTTPHEADER, $headers);
138
            curl_setopt($handler, CURLOPT_POSTFIELDS, $form_data->getFiles());
139
        }
140
    }
141
142
}