Completed
Push — master ( c52910...66a65c )
by lyu
02:53 queued 47s
created

BaseClient::newAopClient()   C

Complexity

Conditions 15
Paths 8

Size

Total Lines 49

Duplication

Lines 49
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 240

Importance

Changes 0
Metric Value
cc 15
nc 8
nop 0
dl 49
loc 49
ccs 0
cts 42
cp 0
crap 240
rs 5.9166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Kaylyu\Alipay\F2fpay\Kernel;
4
5
use GuzzleHttp\MessageFormatter;
6
use GuzzleHttp\Middleware;
7
use Kaylyu\Alipay\F2fpay\Base\Model\Result\AlipayF2FPayResult;
8
use Kaylyu\Alipay\Kernel\Exceptions\Exception;
9
use Kaylyu\Alipay\Kernel\ServiceContainer;
10
use Kaylyu\Alipay\Kernel\Support\Collection;
11
use Kaylyu\Alipay\Kernel\Traits\HasHttpRequests;
12
use Psr\Http\Message\ResponseInterface;
13
14
/**
15
 * Class BaseClient.
16
 */
17
class BaseClient
18
{
19
    use HasHttpRequests {
20
        request as performRequest;
21
    }
22
23
    /**
24
     * @var \Kaylyu\Alipay\Kernel\ServiceContainer
25
     */
26
    protected $app;
27
28
    /**
29
     * @var
30
     */
31
    protected $baseUri;
32
33
    /**
34
     * BaseClient constructor.
35
     *
36
     * @param \Kaylyu\Alipay\Kernel\ServiceContainer $app
37
     */
38
    public function __construct(ServiceContainer $app)
39
    {
40
        $this->app = $app;
41
    }
42
43
    /**
44
     * @param $request
45
     * @param null $appAuthToken
46
     * @author kaylv <[email protected]>
47
     * @return array|Collection|string
48
     */
49
    public function httpPost($request, $appAuthToken = null)
50
    {
51
        return $this->request($request, 'POST', $appAuthToken);
52
    }
53
54
    /**
55
     * @param $request
56
     * @param string $method
57
     * @param null $appAuthToken
58
     * @author kaylv <[email protected]>
59
     * @return array|Collection|string
60
     */
61
    public function request($request, string $method = 'GET', $appAuthToken = null)
62
    {
63
        if (empty($this->middlewares)) {
64
            $this->registerHttpMiddlewares();
65
        }
66
67
        //初始化AopClient
68
        $aop = $this->newAopClient();
69
70
        //准备请求参数
71
        list($requestUrl, $apiParams) = $aop->requestPrepare($request, null, $appAuthToken);
72
73
        //发起HTTP请求
74
        $key = 'query';
75
        if ($method == 'POST') {
76
            $key = 'form_params';
77
        }
78
        $response = $this->performRequest($requestUrl, $method, [$key => $apiParams]);
79
80
        //验签解密
81
        $response = $aop->responseHandle($request, $response->getBody()->getContents());
82
83
        //
84
        return $response;
85
    }
86
87
    /**
88
     * Register Guzzle middlewares.
89
     */
90
    protected function registerHttpMiddlewares()
91
    {
92
        // log
93
        $this->pushMiddleware($this->logMiddleware(), 'log');
94
    }
95
96
    /**
97
     * Log the request.
98
     *
99
     * @return \Closure
100
     */
101
    protected function logMiddleware()
102
    {
103
        $formatter = new MessageFormatter($this->app['config']['http.log_template'] ?? MessageFormatter::DEBUG);
104
105
        return Middleware::log($this->app['logger'], $formatter);
106
    }
107
108
    /**
109
     * 初始化AopClient
110
     * @author kaylv <[email protected]>
111
     * @throws Exception
112
     */
113 View Code Duplication
    private function newAopClient()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
114
    {
115
        //获取当面付配置
116
        $f2fpay = $this->app->getF2fpay();
117
118
        //获取配置参数
119
        $gatewayUrl = $f2fpay['gateway_url'];
120
        $appId = $f2fpay['app_id'];
121
        $signType = $f2fpay['sign_type'];
122
        $rsaPrivateKey = $f2fpay['merchant_private_key'];
123
        $alipayPublicKey = $f2fpay['alipay_public_key'];
124
        $charset = $f2fpay['charset'];
125
        $notifyUrl = $f2fpay['notify_url'];
126
127
        if (empty($appId) || trim($appId) == "") {
128
            throw new Exception("appid should not be NULL!");
129
        }
130
        if (empty($rsaPrivateKey) || trim($rsaPrivateKey) == "") {
131
            throw new Exception("merchant_private_key should not be NULL!");
132
        }
133
        if (empty($alipayPublicKey) || trim($alipayPublicKey) == "") {
134
            throw new Exception("alipay_public_key should not be NULL!");
135
        }
136
        if (empty($charset) || trim($charset) == "") {
137
            throw new Exception("charset should not be NULL!");
138
        }
139
        if (empty($notifyUrl) || trim($notifyUrl) == "") {
140
            throw new Exception("sign_type should not be NULL");
141
        }
142
        if (empty($gatewayUrl) || trim($gatewayUrl) == "") {
143
            throw new Exception("gateway_url should not be NULL");
144
        }
145
        if (empty($signType) || trim($signType) == "") {
146
            throw new Exception("sign_type should not be NULL");
147
        }
148
149
        //组装请求数据
150
        $aop = new AopClient();
151
        $aop->gatewayUrl = $gatewayUrl;
152
        $aop->appId =$appId;
153
        $aop->signType = $signType;
154
        $aop->rsaPrivateKey = $rsaPrivateKey;
155
        $aop->alipayrsaPublicKey = $alipayPublicKey;
156
        $aop->apiVersion = "1.0";
157
        $aop->charset = $charset;
0 ignored issues
show
Bug introduced by
The property charset does not seem to exist. Did you mean postCharset?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
158
        $aop->format = 'json';
159
160
        return $aop;
161
    }
162
163
    /**
164
     * 格式化返回数据
165
     * @param $response
166
     * @author kaylv <[email protected]>
167
     * @return array|Collection|string
168
     */
169
    protected function formatResponseToType($response)
170
    {
171
        //获取数据
172
        $data = is_object($response) ? (array)$response : $response;
173
        //返回数据类型
174
        $type = $this->app->config->get('response_type');
175
176
        switch ($type ?? 'array') {
177
            default:
178
            case 'collection':
179
                return new Collection($data);
180
            case 'array':
181
                return $data;
182
            case 'object':
183
                return $response;
184
            case 'json':
185
                return json_encode($data, JSON_UNESCAPED_UNICODE);
186
        }
187
    }
188
}
189