Passed
Push — main ( 5be1cc...a3fefa )
by Dylan
01:51
created

Curl::setIsFileUpload()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace Lifeboat\SDK\Services;
4
5
use Lifeboat\SDK\CurlResponse;
6
use LogicException;
7
use InvalidArgumentException;
8
9
/**
10
 * Class Curl
11
 * @package Lifeboat\SDK
12
 */
13
class Curl {
14
15
    const ALLOWED_METHODS   = ['GET', 'POST', 'DELETE', 'PUT'];
16
    const USER_AGENT        = 'LifeboatSDK/curl-service';
17
18
    private static $_cache = [];
19
20
    private $_method    = 'GET';
21
    private $_url       = '';
22
    private $_data      = [];
23
    private $_isfile    = false;
24
    private $_headers   = [
25
        'Content-Type'      => 'application/x-www-form-urlencoded',
26
        'X-Requested-By'    => self::USER_AGENT
27
    ];
28
    private $_enable_cache = false;
29
30
    /**
31
     * Curl constructor.
32
     *
33
     * @param string $url
34
     * @param array $data
35
     * @param array $headers
36
     *
37
     * @throws LogicException
38
     */
39
    public function __construct(string $url = null, array $data = [], array $headers = [])
40
    {
41
        if (!is_null($url)) $this->setURL($url);
42
        foreach ($data as $name => $value)      $this->addDataParam($name, $value);
43
        foreach ($headers as $name => $value)   $this->addHeader($name, $value);
44
    }
45
46
    /**
47
     * @param string $url
48
     * @return Curl
49
     */
50
    public function setURL(string $url): Curl
51
    {
52
        $this->_url = $url;
53
        return $this;
54
    }
55
56
    /**
57
     * @return string
58
     */
59
    public function getURL(): string
60
    {
61
        return $this->_url;
62
    }
63
64
    /**
65
     * @param string $method
66
     * @return $this
67
     * @throws InvalidArgumentException If $method specified is invalid
68
     */
69
    public function setMethod(string $method = 'GET'): Curl
70
    {
71
        if (!in_array($method, self::ALLOWED_METHODS)) {
72
            throw new InvalidArgumentException("HTTP Method '{$method}' is not allowed");
73
        }
74
75
        $this->_method = $method;
76
        return $this;
77
    }
78
79
    /**
80
     * @return string
81
     */
82
    public function getMethod(): string
83
    {
84
        return $this->_method;
85
    }
86
87
    /**
88
     * @param string $name
89
     * @param mixed $value
90
     * @return $this
91
     */
92
    public function addDataParam(string $name, $value): Curl
93
    {
94
        $this->_data[$name] = $value;
95
        return $this;
96
    }
97
98
    public function removeDataParam(string $name): Curl
99
    {
100
        if (array_key_exists($name, $this->_data)) unset($this->_data[$name]);
101
        return $this;
102
    }
103
104
    /**
105
     * @return array
106
     */
107
    public function getDataParams(): array
108
    {
109
        return $this->_data;
110
    }
111
112
    /**
113
     * @param string $name
114
     * @param string $value
115
     * @return Curl
116
     */
117
    public function addHeader(string $name, string $value): Curl
118
    {
119
        $this->_headers[$name] = $value;
120
        return $this;
121
    }
122
123
    /**
124
     * @param string $name
125
     * @return Curl
126
     */
127
    public function removeHeader(string $name): Curl
128
    {
129
        if (array_key_exists($name, $this->_headers)) unset($this->_headers[$name]);
130
        return $this;
131
    }
132
133
    /**
134
     * @return array
135
     */
136
    public function getHeaders(): array
137
    {
138
        return $this->_headers;
139
    }
140
141
    public function setIsFileUpload(bool $is_file): Curl
142
    {
143
        $this->addHeader('Content-Type', 'multipart/form-data');
144
        $this->_isfile = $is_file;
145
        return $this;
146
    }
147
148
    public function isFileUpload(): bool
149
    {
150
        return $this->_isfile;
151
    }
152
153
    /**
154
     * @param bool $switch
155
     * @return $this
156
     */
157
    public function cacheRequests(bool $switch): Curl
158
    {
159
        $this->_enable_cache = $switch;
160
        return $this;
161
    }
162
163
    /**
164
     * @return CurlResponse
165
     */
166
    public function curl(): CurlResponse
167
    {
168
        $post_data      = null;
169
        $send_headers   = [];
170
        $request_uri    = $this->getURL();
171
172
        //  Headers
173
        foreach ($this->getHeaders() as $k => $v) $send_headers[] = "{$k}: {$v}";
174
175
        // Request Data
176
        switch ($this->getMethod()) {
177
            case 'GET':
178
            case 'DELETE':
179
                foreach ($this->getDataParams() as $name => $value) $request_uri = HTTP::setGetVar($name, $value, $request_uri);
0 ignored issues
show
Bug introduced by
The type Lifeboat\SDK\Services\HTTP was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
180
                break;
181
182
            case 'POST':
183
                $post_data = ($this->isFileUpload()) ? $this->getDataParams() : http_build_query($this->getDataParams());
184
                break;
185
            case 'PUT':
186
                $post_data = http_build_query($this->getDataParams());
187
                break;
188
        }
189
190
        if ($this->_enable_cache && $this->getMethod() === 'GET') {
191
            $cache_key = urlencode($request_uri) . implode(',', $send_headers);
192
            if (array_key_exists($cache_key, self::$_cache)) {
193
                return self::$_cache[$cache_key];
194
            }
195
        }
196
197
        $ch = curl_init();
198
        curl_setopt($ch, CURLOPT_URL, $request_uri);
199
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
200
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->getMethod());
201
        curl_setopt($ch, CURLOPT_USERAGENT, self::USER_AGENT);
202
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
203
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
204
        curl_setopt($ch, CURLOPT_ENCODING, '');
205
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
206
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
207
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
208
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
209
210
        if (!empty($send_headers))  curl_setopt($ch, CURLOPT_HTTPHEADER, $send_headers);
211
        if (!is_null($post_data))   {
212
            curl_setopt($ch, CURLOPT_POST, 1);
213
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
214
        }
215
216
        $result     = curl_exec($ch);
217
        $http_code  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
218
        
219
        $response = new CurlResponse($http_code, $result);
220
        if ($this->_enable_cache && isset($cache_key)) self::$_cache[$cache_key] = $response;
221
222
        return $response;
223
    }
224
225
    /**
226
     * @see Curl::curl()
227
     *
228
     * @return CurlResponse
229
     */
230
    public function curl_json()
231
    {
232
        $this->addHeader('Accept', 'application/json');
233
        return $this->curl();
234
    }
235
236
    /**
237
     * @see $this->curl()
238
     *
239
     * @return CurlResponse
240
     */
241
    public function curl_api()
242
    {
243
        $ouath          = new OAuth();
0 ignored issues
show
Bug introduced by
The type Lifeboat\SDK\Services\OAuth was not found. Did you mean OAuth? If so, make sure to prefix the type with \.
Loading history...
244
        $access_token   = $ouath->getAccessToken();
245
        $site_key       = StoreSelector::get_site_key();
0 ignored issues
show
Bug introduced by
The type Lifeboat\SDK\Services\StoreSelector was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
246
247
        $this->_enable_cache = true;
248
        $this->setURL($this->getURL(true));
0 ignored issues
show
Unused Code introduced by
The call to Lifeboat\SDK\Services\Curl::getURL() has too many arguments starting with true. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

248
        $this->setURL($this->/** @scrutinizer ignore-call */ getURL(true));

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
249
250
        $this->addHeader('access-token', $access_token);
251
        $this->addHeader('site-key', $site_key);
252
253
        return $this->curl_json();
254
    }
255
}
256