Completed
Push — master ( 8787ba...721c87 )
by wannanbigpig
05:01 queued 11s
created

Support::processingApiResult()   B

Complexity

Conditions 11
Paths 20

Size

Total Lines 73
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 49.1975

Importance

Changes 0
Metric Value
cc 11
eloc 47
nc 20
nop 2
dl 0
loc 73
ccs 15
cts 47
cp 0.3191
crap 49.1975
rs 7.3166
c 0
b 0
f 0

How to fix   Long Method    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
 * This file is part of the wannanbigpig/alipay.
4
 *
5
 * (c) wannanbigpig <[email protected]>
6
 *
7
 * This source file is subject to the MIT license that is bundled
8
 * with this source code in the file LICENSE.
9
 */
10
11
namespace WannanBigPig\Alipay\Kernel\Support;
12
13
use GuzzleHttp\MessageFormatter;
14
use GuzzleHttp\Middleware;
15
use Psr\Http\Message\ResponseInterface;
16
use WannanBigPig\Alipay\Kernel\ServiceContainer;
17
use WannanBigPig\Alipay\Kernel\Traits\Helpers;
18
use WannanBigPig\Supports\Http\Response;
19
use WannanBigPig\Supports\Traits\HttpRequest;
20
use WannanBigPig\Supports\Traits\ResponseCastable;
21
22
/**
23
 * Class Support
24
 *
25
 * @author   liuml  <[email protected]>
26
 * @DateTime 2019-07-22  11:10
27
 */
28
class Support
29
{
30
    use Helpers, ResponseCastable, HttpRequest {
0 ignored issues
show
introduced by
The trait WannanBigPig\Supports\Traits\HttpRequest requires some properties which are not provided by WannanBigPig\Alipay\Kernel\Support\Support: $connectTimeout, $baseUri, $timeout
Loading history...
31
        HttpRequest::request as performRequest;
32
    }
33
34
    /**
35
     * @var \WannanBigPig\Alipay\Kernel\ServiceContainer
36
     */
37
    protected $app;
38
39
    /**
40
     * Support constructor.
41
     *
42
     * @param \WannanBigPig\Alipay\Kernel\ServiceContainer $app
43
     */
44 15
    public function __construct(ServiceContainer $app)
45
    {
46 15
        $this->app = $app;
47
48 15
        $this->setHttpClient($this->app['http_client']);
49 15
    }
50
51
    /**
52
     * request.
53
     *
54
     * @param        $endpoint
55
     * @param array  $params
56
     * @param string $method
57
     * @param array  $options
58
     * @param bool   $returnResponse
59
     *
60
     * @return array|object|\Psr\Http\Message\ResponseInterface|\WannanBigPig\Supports\Collection|\WannanBigPig\Supports\Http\Response
61
     *
62
     * @throws \GuzzleHttp\Exception\GuzzleException
63
     * @throws \WannanBigPig\Alipay\Kernel\Exceptions\InvalidSignException
64
     * @throws \WannanBigPig\Supports\Exceptions\InvalidArgumentException
65
     */
66
    public function request($endpoint, $params = [], $method = 'POST', array $options = [], $returnResponse = false)
67
    {
68
        // Get api system parameters
69
        $sysParams = $this->app->apiCommonConfig($endpoint);
70
        // Filter system parameters
71
        $sysParams = array_filter($sysParams, function ($value) {
72
            return !($this->checkEmpty($value));
73
        });
74
        $params = $this->json($params);
75
        // Set the signature
76
        $sysParams['sign'] = $this->generateSign(array_merge($sysParams, $params), $sysParams['sign_type']);
77
        // Set log middleware to record data, Log request and response data to the log file info level
78
        $this->pushMiddleware($this->logMiddleware(), 'log');
79
        // Set http parameter options
80
        $options = array_merge([
81
            'form_params' => $params,
82
            'headers' => [
83
                'content-type' => 'application/x-www-form-urlencoded',
84
                'charset' => $sysParams['charset'],
85
            ],
86
        ], $options);
87
88
        $response = $this->performRequest($method, '?'.http_build_query($sysParams), $options);
89
90
        $arrayBody = \GuzzleHttp\json_decode((string)$response->getBody(), true, 512, JSON_BIGINT_AS_STRING);
91
        $context = \GuzzleHttp\json_encode($this->parserSignSource($arrayBody, $endpoint), JSON_UNESCAPED_UNICODE);
92
93
        // Verify Response Signature
94
        $this->checkResponseSign($context, $arrayBody['sign'] ?? null);
95
96
        return $returnResponse ? $response : $this->handleResponse($response, $context);
97
    }
98
99
    /**
100
     * handleResponse.
101
     *
102
     * @param \Psr\Http\Message\ResponseInterface $response
103
     * @param string|null                         $context
104
     *
105
     * @return array|object|\Psr\Http\Message\ResponseInterface|\WannanBigPig\Supports\Collection|\WannanBigPig\Supports\Http\Response
106
     *
107
     * @throws \WannanBigPig\Supports\Exceptions\InvalidArgumentException
108
     */
109
    public function handleResponse(ResponseInterface $response, string $context = null)
110
    {
111
        $is_build = true;
112
        if ($this->app['config']->get('handle_response', true) && !is_null($context)) {
113
            $response = new Response(
114
                $response->getStatusCode(),
115
                $response->getHeaders(),
116
                $context,
117
                $response->getProtocolVersion(),
118
                $response->getReasonPhrase()
119
            );
120
            $is_build = false;
121
        }
122
123
        return $this->castResponseToType($response, $this->app['config']->get('response_type', 'array'), $is_build);
124
    }
125
126
    /**
127
     * Log the request.
128
     *
129
     * @return \Closure
130
     */
131
    protected function logMiddleware()
132
    {
133
        $formatter = new MessageFormatter($this->app['config']['http.log_template'] ?? MessageFormatter::DEBUG);
134
135
        return Middleware::log($this->app['logger']->getLogger(), $formatter);
136
    }
137
138
    /**
139
     * json.
140
     *
141
     * @param array $data
142
     *
143
     * @return array
144
     */
145 4
    protected function json(array $data): array
146
    {
147 4
        $array = [];
148 4
        if (isset($data['biz_content']) && is_array($data['biz_content'])) {
149 4
            $array['biz_content'] = \GuzzleHttp\json_encode($data['biz_content'], JSON_UNESCAPED_UNICODE);
150
        } else {
151
            return $data;
152
        }
153
154 4
        return $array;
155
    }
156
}
157