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

GeneralPlugin::getRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 6
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yansongda\Pay\Plugin\Unipay;
6
7
use Closure;
8
use Psr\Http\Message\RequestInterface;
9
use Yansongda\Pay\Contract\PluginInterface;
10
11
use function Yansongda\Pay\get_unipay_config;
12
13
use Yansongda\Pay\Logger;
14
use Yansongda\Pay\Pay;
15
use Yansongda\Pay\Provider\Unipay;
16
use Yansongda\Pay\Request;
17
use Yansongda\Pay\Rocket;
18
19
abstract class GeneralPlugin implements PluginInterface
20
{
21
    /**
22
     * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
23
     * @throws \Yansongda\Pay\Exception\ContainerException
24
     */
25
    public function assembly(Rocket $rocket, Closure $next): Rocket
26
    {
27
        Logger::info('[unipay][GeneralPlugin] 通用插件开始装载', ['rocket' => $rocket]);
28
29
        $rocket->setRadar($this->getRequest($rocket));
30
        $this->doSomething($rocket);
31
32
        Logger::info('[unipay][GeneralPlugin] 通用插件装载完毕', ['rocket' => $rocket]);
33
34
        return $next($rocket);
35
    }
36
37
    /**
38
     * @throws \Yansongda\Pay\Exception\ContainerException
39
     * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
40
     */
41
    protected function getRequest(Rocket $rocket): RequestInterface
42
    {
43
        return new Request(
44
            $this->getMethod(),
45
            $this->getUrl($rocket),
46
            $this->getHeaders(),
47
        );
48
    }
49
50
    protected function getMethod(): string
51
    {
52
        return 'POST';
53
    }
54
55
    /**
56
     * @throws \Yansongda\Pay\Exception\ContainerException
57
     * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
58
     */
59
    protected function getUrl(Rocket $rocket): string
60
    {
61
        $url = $this->getUri($rocket);
62
63
        if (0 === strpos($url, 'http')) {
64
            return $url;
65
        }
66
67
        $config = get_unipay_config($rocket->getParams());
68
69
        return Unipay::URL[$config['mode'] ?? Pay::MODE_NORMAL].$url;
70
    }
71
72
    protected function getHeaders(): array
73
    {
74
        return [
75
            'User-Agent' => 'yansongda/pay-v3',
76
            'Content-Type' => 'application/x-www-form-urlencoded;charset=utf-8',
77
        ];
78
    }
79
80
    abstract protected function doSomething(Rocket $rocket): void;
81
82
    abstract protected function getUri(Rocket $rocket): string;
83
}
84