Completed
Pull Request — master (#14)
by Carlos
05:03
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 (\array_merge($files, $form) as $name => $contents) {
111
            $multipart = array_merge($multipart, $this->normalizeMultipartField($name, $contents));
112
        }
113
        
114
        return $this->request($url, 'POST', ['query' => $query, 'multipart' => $multipart]);
115
    }
116
117
    /**
118
     * @param string $uri
119
     * @param string $method
120
     * @param array  $options
121
     * @param bool   $returnRaw
122
     *
123
     * @return \Psr\Http\Message\ResponseInterface|\Overtrue\Http\Support\Collection|array|object|string
124
     */
125
    public function request(string $uri, string $method = 'GET', array $options = [], $returnRaw = false)
126
    {
127
        if (property_exists($this, 'baseUri') && !is_null($this->baseUri)) {
128
            $options['base_uri'] = $this->baseUri;
129
        }
130
131
        if ((!empty($options['base_uri']) || $this->config->getBaseUri()) && $this->config->needAutoTrimEndpointSlash()) {
132
            $uri = ltrim($uri, '/');
133
        }
134
135
        $response = $this->performRequest($uri, $method, $options);
136
137
        return $this->castResponseToType(
138
            $response,
139
            $returnRaw ? 'raw' : $this->config->getOption('response_type')
140
        );
141
    }
142
143
    /**
144
     * @param string $url
145
     * @param string $method
146
     * @param array  $options
147
     *
148
     * @return \Overtrue\Http\Responses\Response
149
     */
150
    public function requestRaw(string $url, string $method = 'GET', array $options = [])
151
    {
152
        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...
153
    }
154
155
    /**
156
     * Return GuzzleHttp\Client instance.
157
     *
158
     * @return \GuzzleHttp\ClientInterface
159
     */
160
    public function getHttpClient(): \GuzzleHttp\ClientInterface
161
    {
162
        if (!$this->httpClient) {
163
            $this->httpClient = new GuzzleClient($this->config->toArray());
164
        }
165
166
        return $this->httpClient;
167
    }
168
169
    /**
170
     * @return \Overtrue\Http\Config
171
     */
172
    public function getConfig(): \Overtrue\Http\Config
173
    {
174
        return $this->config;
175
    }
176
177
    /**
178
     * @param \Overtrue\Http\Config $config
179
     *
180
     * @return \Overtrue\Http\Client
181
     */
182
    public function setConfig(\Overtrue\Http\Config $config): \Overtrue\Http\Client
183
    {
184
        $this->config = $config;
185
186
        return $this;
187
    }
188
189
    /**
190
     * @param string $name
191
     * @param mixed  $contents
192
     *
193
     * @return array
194
     */
195
    public function normalizeMultipartField(string $name, $contents) {
196
        $field = [];
197
198
        if (!is_array($contents)) {
199
            return [compact('name', 'contents')];
200
        } else {
201
            foreach ($contents as $key => $value) {
202
                $key = sprintf('%s[%s]', $name, $key);
203
                $field = array_merge($field, is_array($value) ? $this->normalizeMultipartField($key, $value) : [['name' => $key, 'contents' => $value]]);
204
            }
205
        }
206
207
        return $field;
208
    }
209
210
    /**
211
     * @param mixed $config
212
     *
213
     * @return \Overtrue\Http\Config
214
     */
215
    protected function normalizeConfig($config): \Overtrue\Http\Config
216
    {
217
        if (\is_array($config)) {
218
            $config = new Config($config);
219
        }
220
221
        if (!($config instanceof Config)) {
222
            throw new \InvalidArgumentException('config must be array or instance of Overtrue\Http\Config.');
223
        }
224
225
        return $config;
226
    }
227
}
228