GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( feda6f...a8fc77 )
by Coeus
01:50
created

Twitter::clientParams()   B

Complexity

Conditions 11
Paths 32

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 11
nc 32
nop 0
dl 0
loc 17
rs 7.3166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace anerg\OAuth2\Gateways;
4
5
use anerg\OAuth2\Connector\Gateway;
6
use anerg\OAuth2\Helper\Str;
7
8
class Twitter extends Gateway
9
{
10
    const API_BASE = 'https://api.twitter.com/';
11
12
    private $tokenSecret = '';
13
14
    /**
15
     * 构造函数
16
     *
17
     * @param array $config
18
     */
19
    public function __construct($config = null)
20
    {
21
        parent::__construct($config);
22
        $this->clientParams();
23
    }
24
25
    /**
26
     * 设置客户端请求的参数
27
     *
28
     * @return void
29
     */
30
    private function clientParams()
31
    {
32
        if (isset($this->config['access_token']) && !empty($this->config['access_token'])) {
33
            $this->token['access_token'] = $this->config['access_token'];
34
        }
35
        if (isset($this->config['oauth_token']) && !empty($this->config['oauth_token'])) {
36
            $this->token['oauth_token'] = $this->config['oauth_token'];
37
        }
38
        if (isset($this->config['oauth_token_secret']) && !empty($this->config['oauth_token_secret'])) {
39
            $this->token['oauth_token_secret'] = $this->config['oauth_token_secret'];
40
            $this->tokenSecret                 = $this->config['oauth_token_secret'];
41
        }
42
        if (isset($this->config['user_id']) && !empty($this->config['user_id'])) {
43
            $this->token['user_id'] = $this->config['user_id'];
44
        }
45
        if (isset($this->config['screen_name']) && !empty($this->config['screen_name'])) {
46
            $this->token['screen_name'] = $this->config['screen_name'];
47
        }
48
    }
49
    /**
50
     * 得到跳转地址
51
     */
52
    public function getRedirectUrl()
53
    {
54
        $oauthToken = $this->call('oauth/request_token', ['oauth_callback' => $this->config['callback']], 'POST');
55
        return self::API_BASE . 'oauth/authenticate?oauth_token=' . $oauthToken['oauth_token'];
56
    }
57
58
    /**
59
     * 获取当前授权用户的openid标识
60
     */
61
    public function openid()
62
    {
63
        $data = $this->userinfoRaw();
64
        return $data['id_str'];
65
    }
66
67
    /**
68
     * 获取格式化后的用户信息
69
     */
70
    public function userinfo()
71
    {
72
        $data = $this->userinfoRaw();
73
74
        $return = [
75
            'openid'  => $data['id_str'],
76
            'channel' => 'twitter',
77
            'nick'    => $data['name'],
78
            'gender'  => 'n', //twitter不返回用户性别
79
            'avatar'  => $data['profile_image_url_https'],
80
        ];
81
        return $return;
82
    }
83
84
    /**
85
     * 获取原始接口返回的用户信息
86
     */
87
    public function userinfoRaw()
88
    {
89
        if (!$this->token) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->token of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
90
            $this->token = $this->getAccessToken();
91
            if (isset($this->token['oauth_token_secret'])) {
92
                $this->tokenSecret = $this->token['oauth_token_secret'];
93
            } else {
94
                throw new \Exception("获取Twitter ACCESS_TOKEN 出错:" . json_encode($this->token));
95
            }
96
        }
97
98
        return $this->call('1.1/users/show.json', $this->token, 'GET', true);
99
    }
100
101
    /**
102
     * 发起请求
103
     *
104
     * @param string $api
105
     * @param array $params
106
     * @param string $method
107
     * @return array
108
     */
109
    private function call($api, $params = [], $method = 'GET', $isJson = false)
110
    {
111
        $method  = strtoupper($method);
112
        $request = [
113
            'method' => $method,
114
            'uri'    => self::API_BASE . $api,
115
        ];
116
        $oauthParams                    = $this->getOAuthParams($params);
117
        $oauthParams['oauth_signature'] = $this->signature($request, $oauthParams);
118
119
        $headers = ['Authorization' => $this->getAuthorizationHeader($oauthParams)];
120
121
        $data = $this->$method($request['uri'], $params, $headers);
122
        if ($isJson) {
123
            return json_decode($data, true);
124
        }
125
        parse_str($data, $data);
126
        return $data;
127
    }
128
129
    /**
130
     * 获取oauth参数
131
     *
132
     * @param array $params
133
     * @return array
134
     */
135
    private function getOAuthParams($params = [])
136
    {
137
        $_default = [
138
            'oauth_consumer_key'     => $this->config['app_id'],
139
            'oauth_nonce'            => Str::random(),
140
            'oauth_signature_method' => 'HMAC-SHA1',
141
            'oauth_timestamp'        => $this->timestamp,
142
            'oauth_token'            => '',
143
            'oauth_version'          => '1.0',
144
        ];
145
        return array_merge($_default, $params);
146
    }
147
148
    /**
149
     * 签名操作
150
     *
151
     * @param array $request
152
     * @param array $params
153
     * @return string
154
     */
155
    private function signature($request, $params = [])
156
    {
157
        ksort($params);
158
        $sign_str = Str::buildParams($params, true);
159
        $sign_str = $request['method'] . '&' . rawurlencode($request['uri']) . '&' . rawurlencode($sign_str);
160
        $sign_key = $this->config['app_secret'] . '&' . $this->tokenSecret;
161
162
        return rawurlencode(base64_encode(hash_hmac('sha1', $sign_str, $sign_key, true)));
163
    }
164
165
    /**
166
     * 获取请求附带的Header头信息
167
     *
168
     * @param array $params
169
     * @return string
170
     */
171
    private function getAuthorizationHeader($params)
172
    {
173
        $return = 'OAuth ';
174
        foreach ($params as $k => $param) {
175
            $return .= $k . '="' . $param . '", ';
176
        }
177
        return rtrim($return, ', ');
178
    }
179
180
    /**
181
     * 获取access token
182
     * twitter不是标准的oauth2
183
     *
184
     * @return array
185
     */
186
    protected function getAccessToken()
187
    {
188
        return $this->call('oauth/access_token', $_GET, 'POST');
189
    }
190
}
191