Completed
Push — master ( ebf29d...906195 )
by Márk
02:05
created

Client::configureDefaults()   D

Complexity

Conditions 9
Paths 48

Size

Total Lines 44
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 23
nc 48
nop 1
dl 0
loc 44
rs 4.909
c 0
b 0
f 0
1
<?php
2
namespace GuzzleHttp;
3
4
use GuzzleHttp\Cookie\CookieJar;
5
use GuzzleHttp\Promise;
6
use GuzzleHttp\Psr7;
7
use Psr\Http\Message\UriInterface;
8
use Psr\Http\Message\RequestInterface;
9
use Psr\Http\Message\ResponseInterface;
10
11
/**
12
 * @method ResponseInterface get(string|UriInterface $uri, array $options = [])
13
 * @method ResponseInterface head(string|UriInterface $uri, array $options = [])
14
 * @method ResponseInterface put(string|UriInterface $uri, array $options = [])
15
 * @method ResponseInterface post(string|UriInterface $uri, array $options = [])
16
 * @method ResponseInterface patch(string|UriInterface $uri, array $options = [])
17
 * @method ResponseInterface delete(string|UriInterface $uri, array $options = [])
18
 * @method Promise\PromiseInterface getAsync(string|UriInterface $uri, array $options = [])
19
 * @method Promise\PromiseInterface headAsync(string|UriInterface $uri, array $options = [])
20
 * @method Promise\PromiseInterface putAsync(string|UriInterface $uri, array $options = [])
21
 * @method Promise\PromiseInterface postAsync(string|UriInterface $uri, array $options = [])
22
 * @method Promise\PromiseInterface patchAsync(string|UriInterface $uri, array $options = [])
23
 * @method Promise\PromiseInterface deleteAsync(string|UriInterface $uri, array $options = [])
24
 */
25
class Client implements ClientInterface
26
{
27
    /** @var array Default request options */
28
    private $config;
29
30
    /**
31
     * Clients accept an array of constructor parameters.
32
     *
33
     * Here's an example of creating a client using a base_uri and an array of
34
     * default request options to apply to each request:
35
     *
36
     *     $client = new Client([
37
     *         'base_uri'        => 'http://www.foo.com/1.0/',
38
     *         'timeout'         => 0,
39
     *         'allow_redirects' => false,
40
     *         'proxy'           => '192.168.16.1:10'
41
     *     ]);
42
     *
43
     * Client configuration settings include the following options:
44
     *
45
     * - handler: (callable) Function that transfers HTTP requests over the
46
     *   wire. The function is called with a Psr7\Http\Message\RequestInterface
47
     *   and array of transfer options, and must return a
48
     *   GuzzleHttp\Promise\PromiseInterface that is fulfilled with a
49
     *   Psr7\Http\Message\ResponseInterface on success. "handler" is a
50
     *   constructor only option that cannot be overridden in per/request
51
     *   options. If no handler is provided, a default handler will be created
52
     *   that enables all of the request options below by attaching all of the
53
     *   default middleware to the handler.
54
     * - base_uri: (string|UriInterface) Base URI of the client that is merged
55
     *   into relative URIs. Can be a string or instance of UriInterface.
56
     * - **: any request option
57
     *
58
     * @param array $config Client configuration settings.
59
     *
60
     * @see \GuzzleHttp\RequestOptions for a list of available request options.
61
     */
62
    public function __construct(array $config = [])
63
    {
64
        if (!isset($config['handler'])) {
65
            $config['handler'] = HandlerStack::create();
66
        }
67
68
        // Convert the base_uri to a UriInterface
69
        if (isset($config['base_uri'])) {
70
            $config['base_uri'] = Psr7\uri_for($config['base_uri']);
71
        }
72
73
        $this->configureDefaults($config);
74
    }
75
76
    public function __call($method, $args)
77
    {
78
        if (count($args) < 1) {
79
            throw new \InvalidArgumentException('Magic request methods require a URI and optional options array');
80
        }
81
82
        $uri = $args[0];
83
        $opts = isset($args[1]) ? $args[1] : [];
84
85
        return substr($method, -5) === 'Async'
86
            ? $this->requestAsync(substr($method, 0, -5), $uri, $opts)
87
            : $this->request($method, $uri, $opts);
88
    }
89
90
    public function sendAsync(RequestInterface $request, array $options = [])
91
    {
92
        // Merge the base URI into the request URI if needed.
93
        $options = $this->prepareDefaults($options);
94
95
        return $this->transfer(
96
            $request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')),
97
            $options
98
        );
99
    }
100
101
    public function send(RequestInterface $request, array $options = [])
102
    {
103
        $options[RequestOptions::SYNCHRONOUS] = true;
104
        return $this->sendAsync($request, $options)->wait();
105
    }
106
107
    public function requestAsync($method, $uri = '', array $options = [])
108
    {
109
        $options = $this->prepareDefaults($options);
110
        // Remove request modifying parameter because it can be done up-front.
111
        $headers = isset($options['headers']) ? $options['headers'] : [];
112
        $body = isset($options['body']) ? $options['body'] : null;
113
        $version = isset($options['version']) ? $options['version'] : '1.1';
114
        // Merge the URI into the base URI.
115
        $uri = $this->buildUri($uri, $options);
116
        if (is_array($body)) {
117
            $this->invalidBody();
118
        }
119
        $request = new Psr7\Request($method, $uri, $headers, $body, $version);
120
        // Remove the option so that they are not doubly-applied.
121
        unset($options['headers'], $options['body'], $options['version']);
122
123
        return $this->transfer($request, $options);
124
    }
125
126
    public function request($method, $uri = '', array $options = [])
127
    {
128
        $options[RequestOptions::SYNCHRONOUS] = true;
129
        return $this->requestAsync($method, $uri, $options)->wait();
130
    }
131
132
    public function getConfig($option = null)
133
    {
134
        return $option === null
135
            ? $this->config
136
            : (isset($this->config[$option]) ? $this->config[$option] : null);
137
    }
138
139
    private function buildUri($uri, array $config)
140
    {
141
        // for BC we accept null which would otherwise fail in uri_for
142
        $uri = Psr7\uri_for($uri === null ? '' : $uri);
143
144
        if (isset($config['base_uri'])) {
145
            $uri = Psr7\Uri::resolve(Psr7\uri_for($config['base_uri']), $uri);
146
        }
147
148
        return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri;
149
    }
150
151
    /**
152
     * Configures the default options for a client.
153
     *
154
     * @param array $config
155
     */
156
    private function configureDefaults(array $config)
157
    {
158
        $defaults = [
159
            'allow_redirects' => RedirectMiddleware::$defaultSettings,
160
            'http_errors'     => true,
161
            'decode_content'  => true,
162
            'verify'          => true,
163
            'cookies'         => false
164
        ];
165
166
        // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set.
167
168
        // We can only trust the HTTP_PROXY environment variable in a CLI
169
        // process due to the fact that PHP has no reliable mechanism to
170
        // get environment variables that start with "HTTP_".
171
        if (php_sapi_name() == 'cli' && getenv('HTTP_PROXY')) {
172
            $defaults['proxy']['http'] = getenv('HTTP_PROXY');
173
        }
174
175
        if ($proxy = getenv('HTTPS_PROXY')) {
176
            $defaults['proxy']['https'] = $proxy;
177
        }
178
179
        if ($noProxy = getenv('NO_PROXY')) {
180
            $cleanedNoProxy = str_replace(' ', '', $noProxy);
181
            $defaults['proxy']['no'] = explode(',', $cleanedNoProxy);
182
        }
183
184
        $this->config = $config + $defaults;
185
186
        if (!empty($config['cookies']) && $config['cookies'] === true) {
187
            $this->config['cookies'] = new CookieJar();
188
        }
189
190
        // Add the default user-agent header.
191
        if (!isset($this->config['headers'])) {
192
            $this->config['headers'] = ['User-Agent' => default_user_agent()];
193
        } else {
194
            $lowercasedHeaders = array_change_key_case($this->config['headers'], CASE_LOWER);
195
            if (!isset($lowercasedHeaders['user-agent'])) {
196
                $this->config['headers']['User-Agent'] = default_user_agent();
197
            }
198
        }
199
    }
200
201
    /**
202
     * Merges default options into the array.
203
     *
204
     * @param array $options Options to modify by reference
205
     *
206
     * @return array
207
     */
208
    private function prepareDefaults($options)
209
    {
210
        $defaults = $this->config;
211
212
        if (!empty($defaults['headers'])) {
213
            // Default headers are only added if they are not present.
214
            $defaults['_conditional'] = $defaults['headers'];
215
            unset($defaults['headers']);
216
        }
217
218
        // Special handling for headers is required as they are added as
219
        // conditional headers and as headers passed to a request ctor.
220
        if (array_key_exists('headers', $options)) {
221
            // Allows default headers to be unset.
222
            if ($options['headers'] === null) {
223
                $defaults['_conditional'] = null;
224
                unset($options['headers']);
225
            } elseif (!is_array($options['headers'])) {
226
                throw new \InvalidArgumentException('headers must be an array');
227
            }
228
        }
229
230
        // Shallow merge defaults underneath options.
231
        $result = $options + $defaults;
232
233
        // Remove null values.
234
        return array_filter($result, function ($value) {
235
            return !is_null($value);
236
        });
237
    }
238
239
    /**
240
     * Transfers the given request and applies request options.
241
     *
242
     * The URI of the request is not modified and the request options are used
243
     * as-is without merging in default options.
244
     *
245
     * @param RequestInterface $request
246
     * @param array            $options
247
     *
248
     * @return Promise\PromiseInterface
249
     */
250
    private function transfer(RequestInterface $request, array $options)
251
    {
252
        // save_to -> sink
253
        if (isset($options['save_to'])) {
254
            $options['sink'] = $options['save_to'];
255
            unset($options['save_to']);
256
        }
257
258
        // exceptions -> http_errors
259
        if (isset($options['exceptions'])) {
260
            $options['http_errors'] = $options['exceptions'];
261
            unset($options['exceptions']);
262
        }
263
264
        $request = $this->applyOptions($request, $options);
265
        $handler = $options['handler'];
266
267
        try {
268
            return Promise\promise_for($handler($request, $options));
269
        } catch (\Exception $e) {
270
            return Promise\rejection_for($e);
271
        }
272
    }
273
274
    /**
275
     * Applies the array of request options to a request.
276
     *
277
     * @param RequestInterface $request
278
     * @param array            $options
279
     *
280
     * @return RequestInterface
281
     */
282
    private function applyOptions(RequestInterface $request, array &$options)
283
    {
284
        $modify = [];
285
286
        if (isset($options['form_params'])) {
287
            if (isset($options['multipart'])) {
288
                throw new \InvalidArgumentException('You cannot use '
289
                    . 'form_params and multipart at the same time. Use the '
290
                    . 'form_params option if you want to send application/'
291
                    . 'x-www-form-urlencoded requests, and the multipart '
292
                    . 'option to send multipart/form-data requests.');
293
            }
294
            $options['body'] = http_build_query($options['form_params'], '', '&');
295
            unset($options['form_params']);
296
            $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded';
297
        }
298
299
        if (isset($options['multipart'])) {
300
            $options['body'] = new Psr7\MultipartStream($options['multipart']);
0 ignored issues
show
Documentation introduced by
$options['multipart'] is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
301
            unset($options['multipart']);
302
        }
303
304
        if (isset($options['json'])) {
305
            $options['body'] = \GuzzleHttp\json_encode($options['json']);
306
            unset($options['json']);
307
            $options['_conditional']['Content-Type'] = 'application/json';
308
        }
309
310
        if (!empty($options['decode_content'])
311
            && $options['decode_content'] !== true
312
        ) {
313
            $modify['set_headers']['Accept-Encoding'] = $options['decode_content'];
314
        }
315
316
        if (isset($options['headers'])) {
317
            if (isset($modify['set_headers'])) {
318
                $modify['set_headers'] = $options['headers'] + $modify['set_headers'];
319
            } else {
320
                $modify['set_headers'] = $options['headers'];
321
            }
322
            unset($options['headers']);
323
        }
324
325
        if (isset($options['body'])) {
326
            if (is_array($options['body'])) {
327
                $this->invalidBody();
328
            }
329
            $modify['body'] = Psr7\stream_for($options['body']);
330
            unset($options['body']);
331
        }
332
333
        if (!empty($options['auth']) && is_array($options['auth'])) {
334
            $value = $options['auth'];
335
            $type = isset($value[2]) ? strtolower($value[2]) : 'basic';
336
            switch ($type) {
337
                case 'basic':
338
                    $modify['set_headers']['Authorization'] = 'Basic '
339
                        . base64_encode("$value[0]:$value[1]");
340
                    break;
341
                case 'digest':
342
                    // @todo: Do not rely on curl
343
                    $options['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_DIGEST;
344
                    $options['curl'][CURLOPT_USERPWD] = "$value[0]:$value[1]";
345
                    break;
346
            }
347
        }
348
349
        if (isset($options['query'])) {
350
            $value = $options['query'];
351
            if (is_array($value)) {
352
                $value = http_build_query($value, null, '&', PHP_QUERY_RFC3986);
353
            }
354
            if (!is_string($value)) {
355
                throw new \InvalidArgumentException('query must be a string or array');
356
            }
357
            $modify['query'] = $value;
358
            unset($options['query']);
359
        }
360
361
        // Ensure that sink is not an invalid value.
362
        if (isset($options['sink'])) {
363
            // TODO: Add more sink validation?
364
            if (is_bool($options['sink'])) {
365
                throw new \InvalidArgumentException('sink must not be a boolean');
366
            }
367
        }
368
369
        $request = Psr7\modify_request($request, $modify);
370
        if ($request->getBody() instanceof Psr7\MultipartStream) {
371
            // Use a multipart/form-data POST if a Content-Type is not set.
372
            $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary='
373
                . $request->getBody()->getBoundary();
374
        }
375
376
        // Merge in conditional headers if they are not present.
377
        if (isset($options['_conditional'])) {
378
            // Build up the changes so it's in a single clone of the message.
379
            $modify = [];
380
            foreach ($options['_conditional'] as $k => $v) {
381
                if (!$request->hasHeader($k)) {
382
                    $modify['set_headers'][$k] = $v;
383
                }
384
            }
385
            $request = Psr7\modify_request($request, $modify);
386
            // Don't pass this internal value along to middleware/handlers.
387
            unset($options['_conditional']);
388
        }
389
390
        return $request;
391
    }
392
393
    private function invalidBody()
394
    {
395
        throw new \InvalidArgumentException('Passing in the "body" request '
396
            . 'option as an array to send a POST request has been deprecated. '
397
            . 'Please use the "form_params" request option to send a '
398
            . 'application/x-www-form-urlencoded request, or a the "multipart" '
399
            . 'request option to send a multipart/form-data request.');
400
    }
401
}
402