Completed
Pull Request — master (#1556)
by wannanbigpig
04:10
created

Application   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 135
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 47
dl 0
loc 135
ccs 24
cts 24
cp 1
rs 10
c 0
b 0
f 0
wmc 12

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getKey() 0 13 3
A __call() 0 3 1
A verifySignature() 0 24 6
A setSubMchId() 0 5 1
A getCertficates() 0 3 1
1
<?php
2
/*
3
 * This file is part of the overtrue/wechat.
4
 *
5
 * (c) overtrue <[email protected]>
6
 *
7
 * This source file is subject to the MIT license that is bundled
8
 * with this source code in the file LICENSE.
9
 */
10
11
namespace EasyWeChat\MicroMerchant;
12
13
use EasyWeChat\BasicService;
14
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
15
use EasyWeChat\Kernel\ServiceContainer;
16
use EasyWeChat\Kernel\Support;
17
use EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidSignException;
18
19
/**
20
 * Class Application.
21
 *
22
 * @author liuml <[email protected]>
23
 *
24
 * @property \EasyWeChat\MicroMerchant\Certficates\Client    $certficates
25
 * @property \EasyWeChat\MicroMerchant\Material\Client       $material
26
 * @property \EasyWeChat\MicroMerchant\MerchantConfig\Client $merchantConfig
27
 * @property \EasyWeChat\MicroMerchant\Withdraw\Client       $withdraw
28
 * @method mixed applyForEnter(array $params)
29
 * @method mixed getStatus(string $applymentId, string $businessCode = '')
30
 * @method mixed upgrade(array $params)
31
 * @method mixed getUpgradeStatus(string $subMchId = '')
32
 */
33
class Application extends ServiceContainer
34
{
35
    /**
36
     * @var array
37
     */
38
    protected $providers = [
39
        // Base services
40
        BasicService\Media\ServiceProvider::class,
41
        Base\ServiceProvider::class,
42
        Certficates\ServiceProvider::class,
43
        MerchantConfig\ServiceProvider::class,
44
        Material\ServiceProvider::class,
45
        Withdraw\ServiceProvider::class,
46
    ];
47
48
    /**
49
     * @var array
50
     */
51
    protected $defaultConfig = [
52
        'http' => [
53
            'base_uri' => 'https://api.mch.weixin.qq.com/',
54
        ],
55
        'log' => [
56
            'default' => 'dev', // 默认使用的 channel,生产环境可以改为下面的 prod
57
            'channels' => [
58
                // 测试环境
59
                'dev' => [
60
                    'driver' => 'single',
61
                    'path' => '/tmp/easywechat.log',
62
                    'level' => 'debug',
63
                ],
64
                // 生产环境
65
                'prod' => [
66
                    'driver' => 'daily',
67
                    'path' => '/tmp/easywechat.log',
68
                    'level' => 'info',
69
                ],
70
            ],
71
        ],
72
    ];
73
74
    /**
75
     * @return string
76
     *
77
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
78
     */
79 6
    public function getKey()
80
    {
81 6
        $key = $this['config']->key;
82
83 6
        if (empty($key)) {
84
            throw new InvalidArgumentException('config key connot be empty.');
85
        }
86
87 6
        if (32 !== strlen($key)) {
88 1
            throw new InvalidArgumentException(sprintf("'%s' should be 32 chars length.", $key));
89
        }
90
91 6
        return $key;
92
    }
93
94
    /**
95
     * get certficates.
96
     *
97
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
98
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
99
     * @throws \EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidExtensionException
100
     * @throws \EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidSignException
101
     * @throws \Psr\SimpleCache\InvalidArgumentException
102
     */
103 1
    public function getCertficates()
104
    {
105 1
        return $this->certficates->get();
106
    }
107
108
    /**
109
     * set sub-mch-id and appid.
110
     *
111
     * @param  string  $sub_mch_id  Identification Number of Small and Micro Businessmen Reported by Service Providers
112
     * @param  string  $appid       Public Account ID of Service Provider
113
     *
114
     * @return $this
115
     */
116 1
    public function setSubMchId(string $sub_mch_id, string $appid = '')
117
    {
118 1
        $this['config']->set('sub_mch_id', $sub_mch_id);
119 1
        $this['config']->set('appid', $appid);
120 1
        return $this;
121
    }
122
123
    /**
124
     * Returning true indicates that the verification is successful, returning false indicates that the signature field does not exist or is empty, and if the signature verification is wrong, the InvalidSignException will be thrown directly.
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 140 characters; contains 241 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
125
     *
126
     * @param  array  $data
127
     *
128
     * @return bool
129
     *
130
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
131
     * @throws \EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidSignException
132
     */
133 2
    public function verifySignature(array $data)
134
    {
135 2
        if (!isset($data['sign']) || empty($data['sign'])) {
136 2
            return false;
137
        }
138
139 1
        $sign = $data['sign'];
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 27 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
140 1
        strlen($sign) > 32 && $signType = 'HMAC-SHA256';
141 1
        unset($data['sign']);
142 1
        $secretKey = $this->getKey();
143
144 1
        if ('HMAC-SHA256' === ($signType ?? 'MD5')) {
145
            $encryptMethod = function ($str) use ($secretKey) {
146
                return hash_hmac('sha256', $str, $secretKey);
147
            };
148
        } else {
149 1
            $encryptMethod = 'md5';
150
        }
151
152 1
        if (Support\generate_sign($data, $secretKey, $encryptMethod) === $sign) {
0 ignored issues
show
Bug introduced by
The function generate_sign was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

152
        if (/** @scrutinizer ignore-call */ Support\generate_sign($data, $secretKey, $encryptMethod) === $sign) {
Loading history...
153 1
            return true;
154
        }
155
156 1
        throw new InvalidSignException('return value signature verification error');
157
    }
158
159
    /**
160
     * @param  string  $name
161
     * @param  array   $arguments
162
     *
163
     * @return mixed
164
     */
165
    public function __call($name, $arguments)
166
    {
167
        return call_user_func_array([$this['base'], $name], $arguments);
168
    }
169
}
170