Passed
Pull Request — master (#662)
by Songda
06:08 queued 04:11
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
10
use function Yansongda\Pay\get_unipay_config;
11
12
use Yansongda\Pay\Logger;
13
use Yansongda\Pay\Rocket;
14
use Yansongda\Pay\Traits\GetUnipayCerts;
15
use Yansongda\Supports\Collection;
16
17
class SignPlugin implements PluginInterface
18
{
19
    use GetUnipayCerts;
20
21
    /**
22
     * @throws \Yansongda\Pay\Exception\ContainerException
23
     * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
24
     * @throws \Yansongda\Pay\Exception\InvalidConfigException
25
     */
26
    public function assembly(Rocket $rocket, Closure $next): Rocket
27
    {
28
        Logger::info('[unipay][PreparePlugin] 插件开始装载', ['rocket' => $rocket]);
29
30
        $payload = $rocket->getPayload()->filter(fn ($v, $k) => 'signature' != $k);
31
        $params = $rocket->getParams();
32
        $config = get_unipay_config($params);
33
34
        if (empty($config['certs']['pkey'])) {
35
            $this->getCertId($params['_config'] ?? 'default', $config);
36
37
            $config = get_unipay_config($params);
38
        }
39
40
        $rocket->mergePayload([
41
            '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

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