Completed
Push — master ( 40113d...1cc7c2 )
by do
03:14
created

BaseClient::jsonDecode()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 7
ccs 0
cts 7
cp 0
crap 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the docodeit/wechat.
5
 *
6
 * (c) docodeit <[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 JinWeChat\Kernel;
13
14
use GuzzleHttp\Client;
15
use JinWeChat\Kernel\Http\Response;
16
use JinWeChat\Kernel\Traits\HasHttpRequests;
17
use Psr\Http\Message\RequestInterface;
18
19
/**
20
 * Class BaseClient.
21
 *
22
 * @author docodeit <[email protected]>
23
 */
24
class BaseClient
25
{
26
    use HasHttpRequests {
27
        request as performRequest;
28
    }
29
30
    /**
31
     * @var \JinWeChat\Kernel\ServiceContainer
32
     */
33
    protected $app;
34
35
    /**
36
     * @var \JinWeChat\Kernel\Contracts\CookiesInterface
37
     */
38
    protected $cookies;
39
40
    /**
41
     * @var string
42
     */
43
    protected $referrer;
44
45
    /**
46
     * @var int
47
     */
48
    protected $token;
49
50
    /**
51
     * @var
52
     */
53
    protected $baseUri;
54
55
    /**
56
     * BaseClient constructor.
57
     *
58
     * @param \JinWeChat\Kernel\ServiceContainer $app
59
     */
60
    public function __construct(ServiceContainer $app)
61
    {
62
        $this->app = $app;
63
        $this->referrer = $app['config']->get('http.base_uri', 'https://mp.weixin.qq.com/');
64
        $this->token = isset($this->app->getConfig()['cookies']['token']) ? $this->app->getConfig()['cookies']['token'] : '';
0 ignored issues
show
Documentation Bug introduced by
It seems like IssetNode ? $this->app->...cookies']['token'] : '' can also be of type string. However, the property $token is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
65
    }
66
67
    /**
68
     * GET request.
69
     *
70
     * @param string $url
71
     * @param array $query
72
     *
73
     *
74
     * @return \Psr\Http\Message\ResponseInterface
75
     */
76
    public function httpGet(string $url, array $query = [])
77
    {
78
        return $this->request($url, 'GET', $query);
79
    }
80
81
    /**
82
     * POST request.
83
     *
84
     * @param string $url
85
     * @param array $data
86
     *
87
     *
88
     * @return \Psr\Http\Message\ResponseInterface
89
     */
90
    public function httpPost(string $url, array $data = [])
91
    {
92
        return $this->request($url, 'POST', ['form_params' => $data]);
93
    }
94
95
    /**
96
     * JSON request.
97
     *
98
     * @param string $url
99
     * @param string|array $data
100
     * @param array $query
101
     *
102
     *
103
     * @return \Psr\Http\Message\ResponseInterface
104
     */
105
    public function httpPostJson(string $url, array $data = [], array $query = [])
106
    {
107
        return $this->request($url, 'POST', ['query' => $query, 'json' => $data]);
108
    }
109
110
    /**
111
     * Upload file.
112
     *
113
     * @param string $url
114
     * @param array $files
115
     * @param array $form
116
     * @param array $query
117
     *
118
     *
119
     * @return \Psr\Http\Message\ResponseInterface
120
     */
121
    public function httpUpload(string $url, array $files = [], array $form = [], array $query = [])
122
    {
123
        $multipart = [];
124
125
        foreach ($files as $name => $path) {
126
            $multipart[] = [
127
                'name' => $name,
128
                'contents' => fopen($path, 'r'),
129
            ];
130
        }
131
132
        foreach ($form as $name => $contents) {
133
            $multipart[] = compact('name', 'contents');
134
        }
135
136
        return $this->request($url, 'POST', ['query' => $query, 'multipart' => $multipart]);
137
    }
138
139
    /**
140
     * @param string $url
141
     * @param string $method
142
     * @param array $options
143
     * @param bool $returnRaw
144
     * @return string
145
     */
146
    public function request(string $url, string $method = 'GET', array $options = [], $returnRaw = false)
147
    {
148
        if (empty($this->middlewares)) {
149
            $this->registerHttpMiddlewares();
150
        }
151
        //options 加入token
152
        if (isset($options['query'])) {
153
            $options['query'] = array_merge($options['query'], ['token' => $this->token]);
154
        }
155
        $response = $this->performRequest($url, $method, $options);
156
        //保存Token todo::改为缓存
157
        if (preg_match('/cgi-bin\/bizlogin?action=startlogin/', $url, $urlMatch)) {
158
            if (preg_match('/token=([\d]+)/i', $response['redirect_url'], $match)) {
159
                $this->token = $match[1];
160
            }
161
        }
162
        return $returnRaw ? $response : $response->getBody()->getContents();
163
    }
164
165
    /**
166
     * @param string $url
167
     * @param string $method
168
     * @param array $options
169
     *
170
     *
171
     * @return \JinWeChat\Kernel\Http\Response
172
     */
173
    public function requestRaw(string $url, string $method = 'GET', array $options = [])
174
    {
175
        return Response::buildFromPsrResponse($this->request($url, $method, $options, true));
176
    }
177
178
    /**
179
     * Return GuzzleHttp\Client instance.
180
     *
181
     * @return \GuzzleHttp\Client
182
     */
183
    public function getHttpClient(): Client
184
    {
185
        if (!($this->httpClient instanceof Client)) {
186
            $this->httpClient = $this->app['http_client'] ?? new Client();
187
        }
188
        return $this->httpClient;
189
    }
190
191
    /**
192
     * Register Guzzle middlewares.
193
     */
194
    protected function registerHttpMiddlewares()
195
    {
196
        //referrer
197
        $this->pushMiddleware($this->headerMiddleware('Referer', $this->referrer), 'referrer');
198
    }
199
200
    /**
201
     * apply referrer to the request header.
202
     *
203
     * @param $header
204
     * @param $value
205
     *
206
     * @return \Closure
207
     */
208
    public function headerMiddleware($header, $value)
209
    {
210
        return function (callable $handler) use ($header, $value) {
211
            return function (
212
                RequestInterface $request,
213
                array $options
214
            ) use (
215
                $handler,
216
                $header,
217
                $value
218
            ) {
219
                $request = $request->withHeader($header, $value);
220
221
                return $handler($request, $options);
222
            };
223
        };
224
    }
225
226
    /**
227
     * 保存Cookies todo::保存到Cache.
228
     */
229
    public function saveCookies()
230
    {
231
        $cookies = $this->app['http_client']->getConfig()['cookies'];
0 ignored issues
show
Unused Code introduced by
The assignment to $cookies is dead and can be removed.
Loading history...
232
    }
233
234
    /**
235
     * 获取微秒.
236
     *
237
     * @return float
238
     */
239
    public function getMillisecond()
240
    {
241
        list($s1, $s2) = explode(' ', microtime());
242
243
        return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
244
    }
245
246
    /**
247
     * 转换json
248
     * @param $json
249
     * @return bool|string
250
     */
251
    public function jsonDecode($json)
252
    {
253
        $res = json_decode($json);
254
        if (JSON_ERROR_NONE == json_last_error()) {
255
            return $res;
256
        } else {
257
            return false;
258
        }
259
    }
260
}
261