Test Failed
Push — master ( 0a62d9...bdd8d4 )
by Carlos
02:27
created

AccessToken::autoRefresh()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
ccs 0
cts 0
cp 0
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the overtrue/wechat.
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
/**
13
 * AccessToken.php.
14
 *
15
 * @author    overtrue <[email protected]>
16
 * @copyright 2015 overtrue <[email protected]>
17
 *
18
 * @see      https://github.com/overtrue
19
 * @see      http://overtrue.me
20
 */
21
22
namespace EasyWeChat\Core;
23
24
use Doctrine\Common\Cache\Cache;
25
use Doctrine\Common\Cache\FilesystemCache;
26
use EasyWeChat\Core\Exceptions\HttpException;
27
28
/**
29
 * Class AccessToken.
30
 */
31
class AccessToken
32
{
33
    /**
34
     * App ID.
35
     *
36
     * @var string
37
     */
38
    protected $appId;
39
40
    /**
41
     * App secret.
42
     *
43
     * @var string
44
     */
45
    protected $secret;
46
47
    /**
48
     * Cache.
49
     *
50
     * @var Cache
51
     */
52
    protected $cache;
53
54
    /**
55
     * Cache Key.
56
     *
57
     * @var string
58
     */
59
    protected $cacheKey;
60
61
    /**
62
     * Http instance.
63
     *
64
     * @var Http
65
     */
66
    protected $http;
67
68
    /**
69
     * Query name.
70
     *
71
     * @var string
72
     */
73
    protected $queryName = 'access_token';
74
75
    /**
76
     * Response Json key name.
77
     *
78
     * @var string
79
     */
80
    protected $tokenJsonKey = 'access_token';
81
82
    /**
83
     * Cache key prefix.
84
     *
85
     * @var string
86
     */
87
    protected $prefix = 'easywechat.common.access_token.';
88
89
    /**
90
     * @var bool
91
     */
92
    protected $autoRefresh = true;
93
94
    // API
95
    const API_TOKEN_GET = 'https://api.weixin.qq.com/cgi-bin/token';
96
97
    /**
98
     * Constructor.
99 61
     *
100
     * @param string                       $appId
101 61
     * @param string                       $secret
102 61
     * @param \Doctrine\Common\Cache\Cache $cache
103 61
     */
104 61
    public function __construct($appId, $secret, Cache $cache = null)
105
    {
106
        $this->appId = $appId;
107
        $this->secret = $secret;
108
        $this->cache = $cache;
109
    }
110
111
    /**
112
     * Get token from WeChat API.
113 5
     *
114
     * @param bool $forceRefresh
115 5
     *
116 5
     * @return string
117
     */
118 5
    public function getToken($forceRefresh = false)
119 2
    {
120
        $cacheKey = $this->getCacheKey();
121
        $cached = $this->getCache()->fetch($cacheKey);
122 2
123
        if ($forceRefresh || empty($cached)) {
124 2
            $token = $this->getTokenFromServer();
125
126
            // XXX: T_T... 7200 - 1500
127 4
            $this->getCache()->save($cacheKey, $token[$this->tokenJsonKey], $token['expires_in'] - 1500);
128
129
            return $token[$this->tokenJsonKey];
130
        }
131
132
        return $cached;
133
    }
134
135
    /**
136
     * 设置自定义 token.
137
     *
138 2
     * @param string $token
139
     * @param int    $expires
140 2
     *
141
     * @return $this
142 2
     */
143
    public function setToken($token, $expires = 7200)
144
    {
145
        $this->getCache()->save($this->getCacheKey(), $token, $expires - 1500);
146
147
        return $this;
148
    }
149
150 20
    /**
151
     * Return the app id.
152 20
     *
153
     * @return string
154
     */
155
    public function getAppId()
156
    {
157
        return $this->appId;
158
    }
159
160 2
    /**
161
     * Return the secret.
162 2
     *
163
     * @return string
164
     */
165
    public function getSecret()
166
    {
167
        return $this->secret;
168
    }
169
170
    /**
171
     * Set cache instance.
172 2
     *
173
     * @param \Doctrine\Common\Cache\Cache $cache
174 2
     *
175
     * @return AccessToken
176 2
     */
177
    public function setCache(Cache $cache)
178
    {
179
        $this->cache = $cache;
180
181
        return $this;
182
    }
183
184 5
    /**
185
     * Return the cache manager.
186 5
     *
187
     * @return \Doctrine\Common\Cache\Cache
188
     */
189
    public function getCache()
190
    {
191
        return $this->cache ?: $this->cache = new FilesystemCache(sys_get_temp_dir());
192
    }
193
194
    /**
195
     * Set the query name.
196 1
     *
197
     * @param string $queryName
198 1
     *
199
     * @return $this
200 1
     */
201
    public function setQueryName($queryName)
202
    {
203
        $this->queryName = $queryName;
204
205
        return $this;
206
    }
207
208 1
    /**
209
     * Return the query name.
210 1
     *
211
     * @return string
212
     */
213
    public function getQueryName()
214
    {
215
        return $this->queryName;
216
    }
217
218 1
    /**
219
     * Return the API request queries.
220 1
     *
221
     * @return array
222
     */
223
    public function getQueryFields()
224
    {
225
        return [$this->queryName => $this->getToken()];
226
    }
227
228
    /**
229
     * Get the access token from WeChat server.
230 2
     *
231
     * @throws \EasyWeChat\Core\Exceptions\HttpException
232
     *
233 2
     * @return string
234 2
     */
235 2 View Code Duplication
    public function getTokenFromServer()
236 2
    {
237
        $params = [
238 2
            'appid' => $this->appId,
239
            'secret' => $this->secret,
240 2
            'grant_type' => 'client_credential',
241
        ];
242 2
243 1
        $http = $this->getHttp();
244
245
        $token = $http->parseJSON($http->get(self::API_TOKEN_GET, $params));
246 2
247
        if (empty($token[$this->tokenJsonKey])) {
248
            throw new HttpException('Request AccessToken fail. response: '.json_encode($token, JSON_UNESCAPED_UNICODE));
249
        }
250
251
        return $token;
252
    }
253
254 2
    /**
255
     * Return the http instance.
256 2
     *
257
     * @return \EasyWeChat\Core\Http
258
     */
259
    public function getHttp()
260
    {
261
        return $this->http ?: $this->http = new Http();
262
    }
263
264
    /**
265
     * Set the http instance.
266 2
     *
267
     * @param \EasyWeChat\Core\Http $http
268 2
     *
269
     * @return $this
270 2
     */
271
    public function setHttp(Http $http)
272
    {
273
        $this->http = $http;
274
275
        return $this;
276
    }
277
278
    /**
279
     * Set the access token prefix.
280
     *
281
     * @param string $prefix
282
     *
283
     * @return $this
284
     */
285
    public function setPrefix($prefix)
286
    {
287
        $this->prefix = $prefix;
288
289
        return $this;
290
    }
291
292
    /**
293
     * Set access token cache key.
294
     *
295
     * @param string $cacheKey
296
     *
297
     * @return $this
298
     */
299
    public function setCacheKey($cacheKey)
300
    {
301
        $this->cacheKey = $cacheKey;
302
303
        return $this;
304
    }
305
306 5
    /**
307
     * Get access token cache key.
308 5
     *
309 5
     * @return string $this->cacheKey
310
     */
311
    public function getCacheKey()
312
    {
313
        if (is_null($this->cacheKey)) {
314
            return $this->prefix.$this->appId;
315
        }
316
317
        return $this->cacheKey;
318
    }
319
320
    /**
321
     * @param bool $enabled
322
     *
323
     * @return $this
324
     */
325
    public function autoRefresh($enabled = true)
326
    {
327
        $this->autoRefresh = $enabled;
328
329
        return $this;
330
    }
331
}
332