Test Setup Failed
Pull Request — master (#606)
by
unknown
03:03
created

Authorization::handleAuthorization()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 10
nc 1
nop 0
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Authorization.php.
4
 *
5
 * Part of Overtrue\WeChat.
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * @author    lixiao <[email protected]>
11
 * @copyright 2016
12
 *
13
 * @see      https://github.com/overtrue
14
 * @see      http://overtrue.me
15
 */
16
17
namespace EasyWeChat\OpenPlatform;
18
19
use Doctrine\Common\Cache\Cache;
20
use EasyWeChat\Core\Exception;
21
use EasyWeChat\OpenPlatform\Components\Authorizer;
22
use EasyWeChat\OpenPlatform\Traits\Caches;
23
use EasyWeChat\Support\Collection;
24
25
class Authorization
26
{
27
28
    use Caches;
29
30
    const CACHE_KEY_ACCESS_TOKEN  = 'easywechat.open_platform.authorizer_access_token';
31
    const CACHE_KEY_REFRESH_TOKEN = 'easywechat.open_platform.authorizer_refresh_token';
32
33
    /**
34
     * Authorizer API.
35
     *
36
     * @var Authorizer
37
     */
38
    private $authorizer;
39
40
    /**
41
     * Open Platform App Id, aka, Component App Id.
42
     *
43
     * @var string
44
     */
45
    private $appId;
46
47
    /**
48
     * Authorizer App Id.
49
     *
50
     * @var string
51
     */
52
    private $authorizerAppId;
53
54
    /**
55
     * Auth code.
56
     *
57
     * @var string
58
     */
59
    private $authCode;
60
61
    public function __construct(Authorizer $authorizer, $appId,
62
                                Cache $cache = null)
63
    {
64
        $this->authorizer = $authorizer;
65
        $this->appId = $appId;
66
        $this->setCache($cache);
0 ignored issues
show
Bug introduced by
It seems like $cache defined by parameter $cache on line 62 can be null; however, EasyWeChat\OpenPlatform\Traits\Caches::setCache() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
67
    }
68
69
    /**
70
     * Sets the authorizer app id.
71
     *
72
     * @param string $authorizerAppId
73
     */
74
    public function setAuthorizerAppId($authorizerAppId)
75
    {
76
        $this->authorizerAppId = $authorizerAppId;
77
    }
78
79
    /**
80
     * Gets the authorizer app id, or throws if not found.
81
     *
82
     * @return string
83
     * @throws Exception
84
     */
85
    public function getAuthorizerAppId()
86
    {
87
        if (! $this->authorizerAppId) {
88
            throw new Exception(
89
                'Authorizer App Id is not present, you may not make the authorization yet.'
90
            );
91
        }
92
93
        return $this->authorizerAppId;
94
    }
95
96
    /**
97
     * Sets the auth code.
98
     *
99
     * @param $code
100
     */
101
    public function setAuthCode($code) {
102
        $this->authCode = $code;
103
    }
104
105
    /**
106
     * Gets the auth code.
107
     *
108
     * @return string
109
     */
110
    public function getAuthCode() {
111
        return $this->authCode;
112
    }
113
114
    /**
115
     * Sets the auth info from the message of the auth event sent by WeChat.
116
     *
117
     * @param Collection $message
118
     */
119
    public function setFromAuthMessage(Collection $message) {
120
        if ($message->has('AuthorizerAppid')) {
121
            $this->setAuthorizerAppId($message->get('AuthorizerAppid'));
122
        }
123
        if ($message->has('AuthorizationCode')) {
124
            $this->setAuthCode($message->get('AuthorizationCode'));
125
        }
126
    }
127
128
    /**
129
     * Handles authorization: calls the API, saves the tokens.
130
     *
131
     * @return Collection
132
     */
133
    public function handleAuthorization()
134
    {
135
        $info = $this->getAuthorizationInfo();
136
137
        $appId = $info['authorization_info']['authorizer_appid'];
138
        $this->setAuthorizerAppId($appId);
139
140
        $this->saveAuthorizerAccessToken($info['authorization_info']);
141
        $this->saveAuthorizerRefreshToken($info['authorization_info']);
142
143
        $authorizerInfo = $this->getAuthorizerInfo();
144
        // Duplicated info.
145
        $authorizerInfo->forget('authorization_info');
146
        $info->merge($authorizerInfo->all());
147
148
        return $info;
149
    }
150
151
    /**
152
     * Handles the authorizer access token: calls the API, saves the token.
153
     *
154
     * @return string The authorizer access token.
155
     */
156
    public function handleAuthorizerAccessToken()
157
    {
158
        $data = $this->authorizer->getAuthorizationToken(
159
            $this->appId,
160
            $this->getAuthorizerRefreshToken()
161
        );
162
163
        $this->saveAuthorizerAccessToken($data);
164
165
        return $data['authorizer_access_token'];
166
    }
167
168
    /**
169
     * Gets the authorization information.
170
     * Like authorizer app id, access token, refresh token, function scope, etc.
171
     *
172
     * @return Collection
173
     */
174
    public function getAuthorizationInfo()
175
    {
176
        $result = $this->authorizer->getAuthorizationInfo($this->getAuthCode());
177
        if (is_array($result)) {
178
            $result = new Collection($result);
179
        }
180
181
        return $result;
182
    }
183
184
    /**
185
     * Gets the authorizer information.
186
     * Like authorizer name, logo, business, etc.
187
     *
188
     * @return Collection
189
     */
190
    public function getAuthorizerInfo()
191
    {
192
        $result = $this->authorizer->getAuthorizerInfo($this->getAuthorizerAppId());
193
        if (is_array($result)) {
194
            $result = new Collection($result);
195
        }
196
197
        return $result;
198
    }
199
200
    /**
201
     * Saves the authorizer access token in cache.
202
     *
203
     * @param Collection|array $data Array structure from WeChat API result.
204
     */
205
    public function saveAuthorizerAccessToken($data)
206
    {
207
        $accessToken = $data['authorizer_access_token'];
208
        // Expiration time, -100 to avoid any delay.
209
        $expire = $data['expires_in'] - 100;
210
211
        $this->set($this->getAuthorizerAccessTokenKey(), $accessToken, $expire);
212
    }
213
214
    /**
215
     * Gets the authorizer access token.
216
     *
217
     * @return string
218
     */
219
    public function getAuthorizerAccessToken()
220
    {
221
        return $this->get($this->getAuthorizerAccessTokenKey());
222
    }
223
224
    /**
225
     * Saves the authorizer refresh token in cache.
226
     *
227
     * @param Collection|array $data Array structure from WeChat API result.
228
     */
229
    public function saveAuthorizerRefreshToken($data)
230
    {
231
        $refreshToken = $data['authorizer_refresh_token'];
232
233
        $this->set($this->getAuthorizerRefreshTokenKey(), $refreshToken);
234
    }
235
236
    /**
237
     * Gets the authorizer refresh token.
238
     *
239
     * @return string
240
     * @throws Exception When refresh token is not present.
241
     */
242
    public function getAuthorizerRefreshToken()
243
    {
244
        if ($token = $this->get($this->getAuthorizerRefreshTokenKey())) {
245
            return $token;
246
        }
247
248
        throw new Exception(
249
            'Authorizer Refresh Token is not present, you may not make the authorization yet.'
250
        );
251
    }
252
253
    /**
254
     * Removes the authorizer access token from cache.
255
     */
256
    public function removeAuthorizerAccessToken() {
257
        $this->remove($this->getAuthorizerAccessTokenKey());
258
    }
259
260
    /**
261
     * Removes the authorizer refresh token from cache.
262
     */
263
    public function removeAuthorizerRefreshToken() {
264
        $this->remove($this->getAuthorizerRefreshTokenKey());
265
    }
266
267
    /**
268
     * Gets the authorizer access token cache key.
269
     *
270
     * @return string
271
     */
272
    public function getAuthorizerAccessTokenKey()
273
    {
274
        return self::CACHE_KEY_ACCESS_TOKEN
275
            . '.' . $this->appId
276
            . '.' . $this->getAuthorizerAppId();
277
    }
278
279
    /**
280
     * Gets the authorizer refresh token cache key.
281
     *
282
     * @return string
283
     */
284
    public function getAuthorizerRefreshTokenKey()
285
    {
286
        return self::CACHE_KEY_REFRESH_TOKEN
287
            . '.' . $this->appId
288
            . '.' . $this->getAuthorizerAppId();
289
    }
290
291
}