Completed
Pull Request — master (#14)
by Carlos
04:22 queued 01:50
created

Client::normalizeMultipartField()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 13
rs 10
cc 4
nc 3
nop 2
1
<?php
2
3
/*
4
 * This file is part of the overtrue/http.
5
 *
6
 * (c) overtrue <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Overtrue\Http;
13
14
use GuzzleHttp\Client as GuzzleClient;
15
use Overtrue\Http\Traits\HasHttpRequests;
16
17
/**
18
 * Class BaseClient.
19
 *
20
 * @author overtrue <[email protected]>
21
 */
22
class Client
23
{
24
    use HasHttpRequests {
25
        request as performRequest;
26
    }
27
28
    /**
29
     * @var \Overtrue\Http\Config
30
     */
31
    protected $config;
32
33
    /**
34
     * @var
35
     */
36
    protected $baseUri;
37
38
    /**
39
     * @return static
40
     */
41
    public static function create(): self
42
    {
43
        return new static(...func_get_args());
0 ignored issues
show
Bug introduced by
func_get_args() is expanded, but the parameter $config of Overtrue\Http\Client::__construct() does not expect variable arguments. ( Ignorable by Annotation )

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

43
        return new static(/** @scrutinizer ignore-type */ ...func_get_args());
Loading history...
44
    }
45
46
    /**
47
     * Client constructor.
48
     *
49
     * @param \Overtrue\Http\Config|array $config
50
     */
51
    public function __construct($config = [])
52
    {
53
        $this->config = $this->normalizeConfig($config);
54
    }
55
56
    /**
57
     * GET request.
58
     *
59
     * @param string $url
60
     * @param array  $query
61
     *
62
     * @return \Psr\Http\Message\ResponseInterface|\Overtrue\Http\Support\Collection|array|object|string
63
     */
64
    public function get(string $url, array $query = [])
65
    {
66
        return $this->request($url, 'GET', ['query' => $query]);
67
    }
68
69
    /**
70
     * POST request.
71
     *
72
     * @param string $url
73
     * @param array  $data
74
     *
75
     * @return \Psr\Http\Message\ResponseInterface|\Overtrue\Http\Support\Collection|array|object|string
76
     */
77
    public function post(string $url, array $data = [])
78
    {
79
        return $this->request($url, 'POST', ['form_params' => $data]);
80
    }
81
82
    /**
83
     * JSON request.
84
     *
85
     * @param string       $url
86
     * @param string|array $data
87
     * @param array        $query
88
     *
89
     * @return \Psr\Http\Message\ResponseInterface|\Overtrue\Http\Support\Collection|array|object|string
90
     */
91
    public function postJson(string $url, array $data = [], array $query = [])
92
    {
93
        return $this->request($url, 'POST', ['query' => $query, 'json' => $data]);
94
    }
95
96
    /**
97
     * Upload file.
98
     *
99
     * @param string $url
100
     * @param array  $files
101
     * @param array  $form
102
     * @param array  $query
103
     *
104
     * @return \Psr\Http\Message\ResponseInterface|\Overtrue\Http\Support\Collection|array|object|string
105
     */
106
    public function upload(string $url, array $files = [], array $form = [], array $query = [])
107
    {
108
        $multipart = [];
109
110
        foreach ($files as $name => $contents) {
111
            $contents = \is_resource($contents) ?: \fopen($contents, 'r');
112
            $multipart[] = \compact('name', 'contents');
113
        }
114
115
        foreach ($form as $name => $contents) {
116
            $multipart = array_merge($multipart, $this->normalizeMultipartField($name, $contents));
117
        }
118
119
        return $this->request($url, 'POST', ['query' => $query, 'multipart' => $multipart]);
120
    }
121
122
    /**
123
     * @param string $uri
124
     * @param string $method
125
     * @param array  $options
126
     * @param bool   $returnRaw
127
     *
128
     * @return \Psr\Http\Message\ResponseInterface|\Overtrue\Http\Support\Collection|array|object|string
129
     */
130
    public function request(string $uri, string $method = 'GET', array $options = [], $returnRaw = false)
131
    {
132
        if (property_exists($this, 'baseUri') && !is_null($this->baseUri)) {
133
            $options['base_uri'] = $this->baseUri;
134
        }
135
136
        if ((!empty($options['base_uri']) || $this->config->getBaseUri()) && $this->config->needAutoTrimEndpointSlash()) {
137
            $uri = ltrim($uri, '/');
138
        }
139
140
        $response = $this->performRequest($uri, $method, $options);
141
142
        return $this->castResponseToType(
143
            $response,
144
            $returnRaw ? 'raw' : $this->config->getOption('response_type')
145
        );
146
    }
147
148
    /**
149
     * @param string $url
150
     * @param string $method
151
     * @param array  $options
152
     *
153
     * @return \Overtrue\Http\Responses\Response
154
     */
155
    public function requestRaw(string $url, string $method = 'GET', array $options = [])
156
    {
157
        return $this->request($url, $method, $options, true);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->request($u...method, $options, true) returns the type Overtrue\Http\Support\Collection which is incompatible with the documented return type Overtrue\Http\Responses\Response.
Loading history...
158
    }
159
160
    /**
161
     * Return GuzzleHttp\Client instance.
162
     *
163
     * @return \GuzzleHttp\ClientInterface
164
     */
165
    public function getHttpClient(): \GuzzleHttp\ClientInterface
166
    {
167
        if (!$this->httpClient) {
168
            $this->httpClient = new GuzzleClient($this->config->toArray());
169
        }
170
171
        return $this->httpClient;
172
    }
173
174
    /**
175
     * @return \Overtrue\Http\Config
176
     */
177
    public function getConfig(): \Overtrue\Http\Config
178
    {
179
        return $this->config;
180
    }
181
182
    /**
183
     * @param \Overtrue\Http\Config $config
184
     *
185
     * @return \Overtrue\Http\Client
186
     */
187
    public function setConfig(\Overtrue\Http\Config $config): \Overtrue\Http\Client
188
    {
189
        $this->config = $config;
190
191
        return $this;
192
    }
193
194
    /**
195
     * @param string $name
196
     * @param mixed  $contents
197
     *
198
     * @return array
199
     */
200
    public function normalizeMultipartField(string $name, $contents) {
201
        $field = [];
202
203
        if (!is_array($contents)) {
204
            return [compact('name', 'contents')];
205
        } else {
206
            foreach ($contents as $key => $value) {
207
                $key = sprintf('%s[%s]', $name, $key);
208
                $field = array_merge($field, is_array($value) ? $this->normalizeMultipartField($key, $value) : [['name' => $key, 'contents' => $value]]);
209
            }
210
        }
211
212
        return $field;
213
    }
214
215
    /**
216
     * @param mixed $config
217
     *
218
     * @return \Overtrue\Http\Config
219
     */
220
    protected function normalizeConfig($config): \Overtrue\Http\Config
221
    {
222
        if (\is_array($config)) {
223
            $config = new Config($config);
224
        }
225
226
        if (!($config instanceof Config)) {
227
            throw new \InvalidArgumentException('config must be array or instance of Overtrue\Http\Config.');
228
        }
229
230
        return $config;
231
    }
232
}
233