Passed
Pull Request — master (#662)
by Songda
01:48
created

SignPlugin::assembly()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 21
rs 9.9
cc 2
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yansongda\Pay\Plugin\Unipay;
6
7
use Closure;
8
use Yansongda\Pay\Contract\PluginInterface;
9
use Yansongda\Pay\Logger;
10
use Yansongda\Pay\Rocket;
11
use Yansongda\Pay\Traits\GetUnipayCerts;
12
use Yansongda\Supports\Collection;
13
14
class SignPlugin implements PluginInterface
15
{
16
    use GetUnipayCerts;
17
18
    /**
19
     * @throws \Yansongda\Pay\Exception\ContainerException
20
     * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
21
     * @throws \Yansongda\Pay\Exception\InvalidConfigException
22
     */
23
    public function assembly(Rocket $rocket, Closure $next): Rocket
24
    {
25
        Logger::info('[unipay][PreparePlugin] 插件开始装载', ['rocket' => $rocket]);
26
27
        $payload = $rocket->getPayload()->filter(fn ($v, $k) => 'signature' != $k);
28
        $params = $rocket->getParams();
29
        $config = get_unipay_config($params);
30
31
        if (empty($config['certs']['pkey'])) {
32
            $this->getCertId($params['_config'] ?? 'default', $config);
33
34
            $config = get_unipay_config($params);
35
        }
36
37
        $rocket->mergePayload([
38
            'signature' => $this->getSign($config['certs']['pkey'] ?? '', $payload),
0 ignored issues
show
Bug introduced by
It seems like $payload can also be of type null; however, parameter $payload of Yansongda\Pay\Plugin\Unipay\SignPlugin::getSign() does only seem to accept Yansongda\Supports\Collection, 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

38
            'signature' => $this->getSign($config['certs']['pkey'] ?? '', /** @scrutinizer ignore-type */ $payload),
Loading history...
39
        ]);
40
41
        Logger::info('[unipay][PreparePlugin] 插件装载完毕', ['rocket' => $rocket]);
42
43
        return $next($rocket);
44
    }
45
46
    protected function getSign(string $pkey, Collection $payload): string
47
    {
48
        $content = $payload->sortKeys()->toString();
49
50
        openssl_sign(hash('sha256', $content), $sign, $pkey, 'sha256');
51
52
        return base64_encode($sign);
53
    }
54
}
55