Completed
Push — master ( 7c0e89...5c9864 )
by Wang
13:40
created

MiniProgramProvider::getAccessToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 14
nc 1
nop 2
1
<?php
2
3
4
namespace Oakhope\OAuth2\Client\Provider;
5
6
use League\OAuth2\Client\Grant\AbstractGrant;
7
use League\OAuth2\Client\Provider\AbstractProvider;
8
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
9
use League\OAuth2\Client\Provider\ResourceOwnerInterface;
10
use League\OAuth2\Client\Tool\ArrayAccessorTrait;
11
use League\OAuth2\Client\Tool\RequiredParameterTrait;
12
use League\OAuth2\Client\Token\AccessToken;
13
use Oakhope\OAuth2\Client\Grant\MiniProgram\AuthorizationCode;
14
use Psr\Http\Message\ResponseInterface;
15
16
class MiniProgramProvider extends AbstractProvider
17
{
18
    use ArrayAccessorTrait;
19
    use RequiredParameterTrait;
20
21
    protected $appid;
22
    protected $secret;
23
    protected $jscode;
24
    protected $responseUserInfo;
25
26
    /**
27
     * Constructs an OAuth 2.0 service provider.
28
     *
29
     * @param array $options An array of options to set on this provider.
30
     *     Options include `clientId`, `clientSecret`, `redirectUri`, and `state`.
31
     *     Individual providers may introduce more options, as needed.
32
     * @param array $collaborators An array of collaborators that may be used to
33
     *     override this provider's default behavior. Collaborators include
34
     *     `grantFactory`, `requestFactory`, and `httpClient`.
35
     *     Individual providers may introduce more collaborators, as needed.
36
     */
37
    public function __construct(array $options = [], array $collaborators = [])
38
    {
39
        $this->checkRequiredParameters(
40
            [
41
                'appid',
42
                'secret',
43
            ],
44
            $options
45
        );
46
47
        $options['access_token'] = 'js_code';
48
49
        parent::__construct($options, $collaborators);
50
    }
51
52
    /**
53
     * Returns the base URL for authorizing a client.
54
     *
55
     * Eg. https://oauth.service.com/authorize
56
     *
57
     * @return string
58
     */
59
    public function getBaseAuthorizationUrl()
60
    {
61
        throw new \LogicException('use wx.login(OBJECT) to get js_code');
62
    }
63
64
    /**
65
     * Returns the base URL for requesting an access token.
66
     *
67
     * Eg. https://oauth.service.com/token
68
     *
69
     * @param array $params
70
     * @return string
71
     */
72
    public function getBaseAccessTokenUrl(array $params)
73
    {
74
        return 'https://api.weixin.qq.com/sns/jscode2session';
75
    }
76
77
    /**
78
     * Requests an access token using a specified grant and option set.
79
     *
80
     * @param  string $jsCode
81
     * @param  array $options
82
     * @return AccessToken
83
     */
84
    public function getAccessToken($jsCode, array $options = [])
85
    {
86
        $this->jscode = $jsCode;
87
        $grant = new AuthorizationCode();
88
        $grant = $this->verifyGrant($grant);
89
        $params = [
90
            'appid' => $this->appid,
91
            'secret' => $this->secret,
92
            'js_code' => $jsCode,
93
        ];
94
95
        $params = $grant->prepareRequestParameters($params, $options);
96
        $request = $this->getAccessTokenRequest($params);
97
        $response = $this->getParsedResponse($request);
98
        $prepared = $this->prepareAccessTokenResponse($response);
0 ignored issues
show
Bug introduced by
It seems like $response defined by $this->getParsedResponse($request) on line 97 can also be of type null or string; however, League\OAuth2\Client\Pro...reAccessTokenResponse() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
99
        $token = $this->createAccessToken($prepared, $grant);
100
101
        return $token;
102
    }
103
104
    /**
105
     * Creates an access token from a response.
106
     *
107
     * The grant that was used to fetch the response can be used to provide
108
     * additional context.
109
     *
110
     * @param  array $response
111
     * @param  AbstractGrant $grant
112
     * @return AccessToken
113
     */
114
    protected function createAccessToken(array $response, AbstractGrant $grant)
115
    {
116
        return new \Oakhope\OAuth2\Client\Token\MiniProgram\AccessToken(
117
            $response
118
        );
119
    }
120
121
    /**
122
     * Returns the URL for requesting the resource owner's details.
123
     *
124
     * @param AccessToken $token
125
     * @return string
126
     */
127
    public function getResourceOwnerDetailsUrl(AccessToken $token)
128
    {
129
        throw new \LogicException(
130
            'use wx.getUserInfo(OBJECT) to get ResourceOwnerDetails'
131
        );
132
    }
133
134
    /**
135
     * Returns the default scopes used by this provider.
136
     *
137
     * This should only be the scopes that are required to request the details
138
     * of the resource owner, rather than all the available scopes.
139
     *
140
     * @return array
141
     */
142
    protected function getDefaultScopes()
143
    {
144
        return [];
145
    }
146
147
    /**
148
     * Checks a provider response for errors.
149
     *
150
     * @throws IdentityProviderException
151
     * @param  ResponseInterface $response
152
     * @param  array|string $data Parsed response data
153
     * @return void
154
     */
155
    protected function checkResponse(ResponseInterface $response, $data)
156
    {
157
        $errcode = $this->getValueByKey($data, 'errcode');
0 ignored issues
show
Bug introduced by
It seems like $data defined by parameter $data on line 155 can also be of type string; however, League\OAuth2\Client\Too...rTrait::getValueByKey() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
158
        $errmsg = $this->getValueByKey($data, 'errmsg');
0 ignored issues
show
Bug introduced by
It seems like $data defined by parameter $data on line 155 can also be of type string; however, League\OAuth2\Client\Too...rTrait::getValueByKey() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
159
160
        if ($errcode || $errmsg) {
161
            throw new IdentityProviderException($errmsg, $errcode, $response);
0 ignored issues
show
Documentation introduced by
$response is of type object<Psr\Http\Message\ResponseInterface>, but the function expects a array|string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
162
        };
163
    }
164
165
    /**
166
     * Generates a resource owner object from a successful resource owner
167
     * details request.
168
     *
169
     * @param  array $response
170
     * @param  AccessToken $token
171
     * @return ResourceOwnerInterface
172
     */
173
    public function createResourceOwner(array $response, AccessToken $token)
174
    {
175
        return new MiniProgramResourceOwner($response, $token, $this->appid);
176
    }
177
178
    /**
179
     * Requests and returns the resource owner of given access token.
180
     *
181
     * @param  AccessToken $token
182
     * @return ResourceOwnerInterface
183
     */
184
    public function getResourceOwner(AccessToken $token)
185
    {
186
        if (null == $this->responseUserInfo) {
187
            throw new \InvalidArgumentException(
188
                "setResponseUserInfo by wx.getUserInfo(OBJECT)'s response data first"
189
            );
190
        }
191
192
        return $this->createResourceOwner($this->responseUserInfo, $token);
193
    }
194
195
    /**
196
     * set by wx.getUserInfo(OBJECT)'s response data
197
     *
198
     * @param string $response
199
     */
200
    public function setResponseUserInfo($response)
201
    {
202
        $this->responseUserInfo = $response;
203
    }
204
}
205