Completed
Push — master ( 19f24e...43354d )
by Carlos
02:58
created

Application   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 181
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 58
dl 0
loc 181
ccs 0
cts 47
cp 0
rs 10
c 0
b 0
f 0
wmc 12

7 Methods

Rating   Name   Duplication   Size   Complexity  
A officialAccount() 0 16 1
A miniProgram() 0 9 1
A __call() 0 3 1
A getMobilePreAuthorizationUrl() 0 19 2
A getReplaceServices() 0 19 4
A getPreAuthorizationUrl() 0 17 2
A getAuthorizerConfig() 0 8 1
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
namespace EasyWeChat\OpenPlatform;
13
14
use EasyWeChat\Kernel\ServiceContainer;
15
use EasyWeChat\MiniProgram\Encryptor;
16
use EasyWeChat\OpenPlatform\Authorizer\Auth\AccessToken;
17
use EasyWeChat\OpenPlatform\Authorizer\MiniProgram\Application as MiniProgram;
18
use EasyWeChat\OpenPlatform\Authorizer\MiniProgram\Auth\Client;
19
use EasyWeChat\OpenPlatform\Authorizer\OfficialAccount\Account\Client as AccountClient;
20
use EasyWeChat\OpenPlatform\Authorizer\OfficialAccount\Application as OfficialAccount;
21
use EasyWeChat\OpenPlatform\Authorizer\OfficialAccount\OAuth\ComponentDelegate;
22
use EasyWeChat\OpenPlatform\Authorizer\Server\Guard;
23
24
/**
25
 * Class Application.
26
 *
27
 * @property \EasyWeChat\OpenPlatform\Server\Guard        $server
28
 * @property \EasyWeChat\OpenPlatform\Auth\AccessToken    $access_token
29
 * @property \EasyWeChat\OpenPlatform\CodeTemplate\Client $code_template
30
 *
31
 * @method mixed handleAuthorize(string $authCode = null)
32
 * @method mixed getAuthorizer(string $appId)
33
 * @method mixed getAuthorizerOption(string $appId, string $name)
34
 * @method mixed setAuthorizerOption(string $appId, string $name, string $value)
35
 * @method mixed getAuthorizers(int $offset = 0, int $count = 500)
36
 * @method mixed createPreAuthorizationCode()
37
 */
38
class Application extends ServiceContainer
39
{
40
    /**
41
     * @var array
42
     */
43
    protected $providers = [
44
        Auth\ServiceProvider::class,
45
        Base\ServiceProvider::class,
46
        Server\ServiceProvider::class,
47
        CodeTemplate\ServiceProvider::class,
48
    ];
49
50
    /**
51
     * @var array
52
     */
53
    protected $defaultConfig = [
54
        'http' => [
55
            'timeout' => 5.0,
56
            'base_uri' => 'https://api.weixin.qq.com/',
57
        ],
58
    ];
59
60
    /**
61
     * Creates the officialAccount application.
62
     *
63
     * @param string                                                    $appId
64
     * @param string|null                                               $refreshToken
65
     * @param \EasyWeChat\OpenPlatform\Authorizer\Auth\AccessToken|null $accessToken
66
     *
67
     * @return \EasyWeChat\OpenPlatform\Authorizer\OfficialAccount\Application
68
     */
69
    public function officialAccount(string $appId, string $refreshToken = null, AccessToken $accessToken = null): OfficialAccount
70
    {
71
        $application = new OfficialAccount($this->getAuthorizerConfig($appId, $refreshToken), $this->getReplaceServices($accessToken) + [
72
            'encryptor' => $this['encryptor'],
73
74
            'account' => function ($app) {
75
                return new AccountClient($app, $this);
76
            },
77
        ]);
78
79
        $application->extend('oauth', function ($socialite) {
80
            /* @var \Overtrue\Socialite\Providers\WeChatProvider $socialite */
81
            return $socialite->component(new ComponentDelegate($this));
82
        });
83
84
        return $application;
85
    }
86
87
    /**
88
     * Creates the miniProgram application.
89
     *
90
     * @param string                                                    $appId
91
     * @param string|null                                               $refreshToken
92
     * @param \EasyWeChat\OpenPlatform\Authorizer\Auth\AccessToken|null $accessToken
93
     *
94
     * @return \EasyWeChat\OpenPlatform\Authorizer\MiniProgram\Application
95
     */
96
    public function miniProgram(string $appId, string $refreshToken = null, AccessToken $accessToken = null): MiniProgram
97
    {
98
        return new MiniProgram($this->getAuthorizerConfig($appId, $refreshToken), $this->getReplaceServices($accessToken) + [
99
            'encryptor' => function () {
100
                return new Encryptor($this['config']['app_id'], $this['config']['token'], $this['config']['aes_key']);
101
            },
102
103
            'auth' => function ($app) {
104
                return new Client($app, $this);
105
            },
106
        ]);
107
    }
108
109
    /**
110
     * Return the pre-authorization login page url.
111
     *
112
     * @param string      $callbackUrl
113
     * @param string|array|null $optional
114
     *
115
     * @return string
116
     */
117
    public function getPreAuthorizationUrl(string $callbackUrl, $optional = []): string
118
    {
119
        // 兼容旧版 API 设计
120
        if (\is_string($optional)) {
121
            $optional = [
122
                'pre_auth_code' => $optional
123
            ];
124
        } else {
125
            $optional['pre_auth_code'] = $this->createPreAuthorizationCode()['pre_auth_code'];
126
        }
127
128
        $queries = \array_merge($optional, [
0 ignored issues
show
Bug introduced by
It seems like $optional can also be of type null; however, parameter $array1 of array_merge() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

128
        $queries = \array_merge(/** @scrutinizer ignore-type */ $optional, [
Loading history...
129
            'component_appid' => $this['config']['app_id'],
130
            'redirect_uri' => $callbackUrl,
131
        ]);
132
133
        return 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?'.http_build_query($queries);
134
    }
135
136
    /**
137
     * Return the pre-authorization login page url (mobile).
138
     *
139
     * @param string      $callbackUrl
140
     * @param string|array|null $optional
141
     *
142
     * @return string
143
     */
144
    public function getMobilePreAuthorizationUrl(string $callbackUrl, $optional = []): string
145
    {
146
        // 兼容旧版 API 设计
147
        if (\is_string($optional)) {
148
            $optional = [
149
                'pre_auth_code' => $optional
150
            ];
151
        } else {
152
            $optional['pre_auth_code'] = $this->createPreAuthorizationCode()['pre_auth_code'];
153
        }
154
155
        $queries = \array_merge($optional, [
0 ignored issues
show
Bug introduced by
It seems like $optional can also be of type null; however, parameter $array1 of array_merge() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

155
        $queries = \array_merge(/** @scrutinizer ignore-type */ $optional, [
Loading history...
156
            'component_appid' => $this['config']['app_id'],
157
            'redirect_uri' => $callbackUrl,
158
            'action' => 'bindcomponent',
159
            'no_scan' => 1,
160
        ]);
161
162
        return 'https://mp.weixin.qq.com/safe/bindcomponent?'.http_build_query($queries).'#wechat_redirect';
163
    }
164
165
    /**
166
     * @param string      $appId
167
     * @param string|null $refreshToken
168
     *
169
     * @return array
170
     */
171
    protected function getAuthorizerConfig(string $appId, string $refreshToken = null): array
172
    {
173
        return [
174
            'debug' => $this['config']->get('debug', false),
175
            'response_type' => $this['config']->get('response_type'),
176
            'log' => $this['config']->get('log', []),
177
            'app_id' => $appId,
178
            'refresh_token' => $refreshToken,
179
        ];
180
    }
181
182
    /**
183
     * @param \EasyWeChat\OpenPlatform\Authorizer\Auth\AccessToken|null $accessToken
184
     *
185
     * @return array
186
     */
187
    protected function getReplaceServices(AccessToken $accessToken = null): array
188
    {
189
        $services = [
190
            'access_token' => $accessToken ?: function ($app) {
191
                return new AccessToken($app, $this);
192
            },
193
194
            'server' => function ($app) {
195
                return new Guard($app);
196
            },
197
        ];
198
199
        foreach (['cache', 'http_client', 'log', 'logger', 'request'] as $reuse) {
200
            if (isset($this[$reuse])) {
201
                $services[$reuse] = $this[$reuse];
202
            }
203
        }
204
205
        return $services;
206
    }
207
208
    /**
209
     * Handle dynamic calls.
210
     *
211
     * @param string $method
212
     * @param array  $args
213
     *
214
     * @return mixed
215
     */
216
    public function __call($method, $args)
217
    {
218
        return call_user_func_array([$this['base'], $method], $args);
219
    }
220
}
221