Completed
Push — master ( 1280db...f286a8 )
by Carlos
03:04
created

AccessToken::setQueryName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
289
290
        return $this;
291
    }
292
293
    /**
294
     * Get access token cache key.
295
     *
296
     * @return string $this->cacheKey
297
     */
298 5
    public function getCacheKey()
299
    {
300 5
        if (is_null($this->cacheKey)) {
301 5
            return $this->prefix.$this->appId;
302
        }
303
304
        return $this->cacheKey;
305
    }
306
}
307