Completed
Push — master ( 8eda0c...ddae51 )
by Carlos
03:01 queued 01:17
created

Client::setHttpClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 5
c 0
b 0
f 0
rs 10
cc 1
nc 1
nop 1
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\Responses\Response;
16
use Overtrue\Http\Traits\HasHttpRequests;
17
18
/**
19
 * Class BaseClient.
20
 *
21
 * @author overtrue <[email protected]>
22
 */
23
class Client
24
{
25
    use HasHttpRequests { request as performRequest; }
26
27
    /**
28
     * @var \Overtrue\Http\Config
29
     */
30
    protected $config;
31
32
    /**
33
     * @var
34
     */
35
    protected $baseUri;
36
37
    /**
38
     * @return static
39
     */
40
    public static function create(): self
41
    {
42
        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

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