Support   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 129
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 43
dl 0
loc 129
ccs 44
cts 44
cp 1
rs 10
c 0
b 0
f 0
wmc 11

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A logMiddleware() 0 5 1
A json() 0 10 3
A request() 0 31 2
A handleResponse() 0 17 4
1
<?php
2
/*
3
 * This file is part of the wannanbigpig/alipay-sdk-php.
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 EasyAlipay\Kernel\Support;
12
13
use EasyAlipay\Kernel\ServiceContainer;
14
use EasyAlipay\Kernel\Traits\Helpers;
15
use GuzzleHttp\MessageFormatter;
16
use GuzzleHttp\Middleware;
17
use Psr\Http\Message\ResponseInterface;
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 {
31
        HttpRequest::request as performRequest;
32
    }
33
34
    /**
35
     * @var \EasyAlipay\Kernel\ServiceContainer
36
     */
37
    protected $app;
38
39
    /**
40
     * Support constructor.
41
     *
42
     * @param \EasyAlipay\Kernel\ServiceContainer $app
43
     */
44 208
    public function __construct(ServiceContainer $app)
45
    {
46 208
        $this->app = $app;
47
48 208
        $this->setHttpClient($this->app['http_client']);
49 208
    }
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 \EasyAlipay\Kernel\Exceptions\InvalidSignException
64
     * @throws \WannanBigPig\Supports\Exceptions\InvalidArgumentException
65
     */
66 2
    public function request($endpoint, $params = [], $method = 'POST', array $options = [], $returnResponse = false)
67
    {
68
        // Get api system parameters
69 2
        $sysParams = $this->app->apiCommonConfig($endpoint);
70
        // Filter system parameters
71 2
        $sysParams = array_filter($sysParams, function ($value) {
72 2
            return !($this->checkEmpty($value));
73 2
        });
74 2
        $params = $this->json($params);
75
        // Set the signature
76 2
        $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 2
        $this->pushMiddleware($this->logMiddleware(), 'log');
79
        // Set http parameter options
80 2
        $options = array_merge([
81 2
            'form_params' => $params,
82
            'headers' => [
83 2
                'content-type' => 'application/x-www-form-urlencoded',
84 2
                'charset' => $sysParams['charset'],
85
            ],
86 2
        ], $options);
87
88 2
        $response = $this->performRequest($method, '?'.http_build_query($sysParams), $options);
89
90 2
        $arrayBody = \GuzzleHttp\json_decode((string)$response->getBody(), true, 512, JSON_BIGINT_AS_STRING);
91 2
        $context = \GuzzleHttp\json_encode($this->parserSignSource($arrayBody, $endpoint), JSON_UNESCAPED_UNICODE);
92
93
        // Verify Response Signature
94 2
        $this->checkResponseSign($context, $arrayBody['sign'] ?? null);
95
96 2
        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 4
    public function handleResponse(ResponseInterface $response, string $context = null)
110
    {
111 4
        $is_build = true;
112 4
        $response_type = $this->app['config']->get('response_type', 'array');
113 4
        $handle_response = $this->app['config']->get('handle_response', true);
114 4
        if ($handle_response && !is_null($context) && $response_type !== 'raw') {
115 4
            $response = new Response(
116 4
                $response->getStatusCode(),
117 4
                $response->getHeaders(),
118 4
                $context,
119 4
                $response->getProtocolVersion(),
120 4
                $response->getReasonPhrase()
121
            );
122 4
            $is_build = false;
123
        }
124
125 4
        return $this->castResponseToType($response, $response_type, $is_build);
126
    }
127
128
    /**
129
     * Log the request.
130
     *
131
     * @return \Closure
132
     */
133 4
    protected function logMiddleware()
134
    {
135 4
        $formatter = new MessageFormatter($this->app['config']['http.log_template'] ?? MessageFormatter::DEBUG);
136
137 4
        return Middleware::log($this->app['logger']->getLogger(), $formatter);
138
    }
139
140
    /**
141
     * json.
142
     *
143
     * @param array $data
144
     *
145
     * @return array
146
     */
147 16
    protected function json(array $data): array
148
    {
149 16
        $array = [];
150 16
        if (isset($data['biz_content']) && is_array($data['biz_content'])) {
151 8
            $array['biz_content'] = \GuzzleHttp\json_encode($data['biz_content'], JSON_UNESCAPED_UNICODE);
152
        } else {
153 8
            return $data;
154
        }
155
156 8
        return $array;
157
    }
158
}
159