Passed
Pull Request — master (#662)
by Songda
02:05
created

CallbackPlugin   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 15
c 1
b 0
f 0
dl 0
loc 37
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A assembly() 0 21 2
A formatPayload() 0 6 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\Exception\Exception;
10
use Yansongda\Pay\Exception\InvalidResponseException;
11
use Yansongda\Pay\Logger;
12
use Yansongda\Pay\Parser\NoHttpRequestParser;
13
use Yansongda\Pay\Rocket;
14
15
use function Yansongda\Pay\verify_unipay_sign;
16
17
use Yansongda\Supports\Collection;
18
use Yansongda\Supports\Str;
19
20
class CallbackPlugin implements PluginInterface
21
{
22
    /**
23
     * @throws \Yansongda\Pay\Exception\ContainerException
24
     * @throws \Yansongda\Pay\Exception\InvalidConfigException
25
     * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
26
     * @throws \Yansongda\Pay\Exception\InvalidResponseException
27
     */
28
    public function assembly(Rocket $rocket, Closure $next): Rocket
29
    {
30
        Logger::info('[unipay][CallbackPlugin] 插件开始装载', ['rocket' => $rocket]);
31
32
        $this->formatPayload($rocket);
33
34
        $params = $rocket->getParams();
35
        $signature = $params['signature'] ?? false;
36
37
        if (!$signature) {
38
            throw new InvalidResponseException(Exception::INVALID_RESPONSE_SIGN, '', $params);
39
        }
40
41
        verify_unipay_sign($params, $rocket->getPayload()->sortKeys()->toString(), $signature);
42
43
        $rocket->setDirection(NoHttpRequestParser::class)
44
            ->setDestination($rocket->getPayload());
45
46
        Logger::info('[unipay][CallbackPlugin] 插件装载完毕', ['rocket' => $rocket]);
47
48
        return $next($rocket);
49
    }
50
51
    protected function formatPayload(Rocket $rocket): void
52
    {
53
        $payload = (new Collection($rocket->getParams()))
54
            ->filter(fn ($v, $k) => 'signature' != $k && !Str::startsWith($k, '_'));
55
56
        $rocket->setPayload($payload);
57
    }
58
}
59