Passed
Push — master ( 5548ec...10f70c )
by Carlos
03:06
created

BaseClient::wrap()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the overtrue/wechat.
5
 *
6
 * (c) overtrue <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace EasyWeChat\Payment\Kernel;
13
14
use EasyWeChat\Kernel\Support;
15
use EasyWeChat\Kernel\Traits\HasHttpRequests;
16
use EasyWeChat\Payment\Application;
17
use GuzzleHttp\MessageFormatter;
18
use GuzzleHttp\Middleware;
19
use Psr\Http\Message\ResponseInterface;
20
21
/**
22
 * Class BaseClient.
23
 *
24
 * @author overtrue <[email protected]>
25
 */
26
class BaseClient
27
{
28
    use HasHttpRequests { request as performRequest; }
0 ignored issues
show
Bug introduced by
The trait EasyWeChat\Kernel\Traits\HasHttpRequests requires the property $baseUri which is not provided by EasyWeChat\Payment\Kernel\BaseClient.
Loading history...
29
30
    /**
31
     * @var \EasyWeChat\Payment\Application
32
     */
33
    protected $app;
34
35
    /**
36
     * Constructor.
37
     *
38
     * @param \EasyWeChat\Payment\Application $app
39
     */
40 44
    public function __construct(Application $app)
41
    {
42 44
        $this->app = $app;
43
44 44
        $this->setHttpClient($this->app['http_client']);
45 44
    }
46
47
    /**
48
     * Extra request params.
49
     *
50
     * @return array
51
     */
52 4
    protected function prepends()
53
    {
54 4
        return [];
55
    }
56
57
    /**
58
     * Make a API request.
59
     *
60
     * @param string $endpoint
61
     * @param array  $params
62
     * @param string $method
63
     * @param array  $options
64
     * @param bool   $returnResponse
65
     *
66
     * @return \Psr\Http\Message\ResponseInterface|\EasyWeChat\Kernel\Support\Collection|array|object|string
67
     *
68
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
69
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
70
     */
71 4
    protected function request(string $endpoint, array $params = [], $method = 'post', array $options = [], $returnResponse = false)
72
    {
73
        $base = [
74 4
            'mch_id' => $this->app['config']['mch_id'],
75 4
            'nonce_str' => uniqid(),
76 4
            'sub_mch_id' => $this->app['config']['sub_mch_id'],
77 4
            'sub_appid' => $this->app['config']['sub_appid'],
78
        ];
79
80 4
        $params = array_filter(array_merge($base, $this->prepends(), $params));
81
82 4
        $secretKey = $this->app->getKey($endpoint);
83 4
        if ('HMAC-SHA256' === ($params['sign_type'] ?? 'MD5')) {
84 1
            $encryptMethod = function ($str) use ($secretKey) {
85 1
                return hash_hmac('sha256', $str, $secretKey);
86 1
            };
87
        } else {
88 3
            $encryptMethod = 'md5';
89
        }
90 4
        $params['sign'] = Support\generate_sign($params, $secretKey, $encryptMethod);
0 ignored issues
show
Bug introduced by
The function generate_sign was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

90
        $params['sign'] = /** @scrutinizer ignore-call */ Support\generate_sign($params, $secretKey, $encryptMethod);
Loading history...
91
92 4
        $options = array_merge([
93 4
            'body' => Support\XML::build($params),
94
        ], $options);
95
96 4
        $this->pushMiddleware($this->logMiddleware(), 'log');
97
98 4
        $response = $this->performRequest($endpoint, $method, $options);
99
100 4
        return $returnResponse ? $response : $this->castResponseToType($response, $this->app->config->get('response_type'));
101
    }
102
103
    /**
104
     * Log the request.
105
     *
106
     * @return \Closure
107
     */
108 4
    protected function logMiddleware()
109
    {
110 4
        $formatter = new MessageFormatter($this->app['config']['http.log_template'] ?? MessageFormatter::DEBUG);
111
112 4
        return Middleware::log($this->app['logger'], $formatter);
113
    }
114
115
    /**
116
     * Make a request and return raw response.
117
     *
118
     * @param string $endpoint
119
     * @param array  $params
120
     * @param string $method
121
     * @param array  $options
122
     *
123
     * @return ResponseInterface
124
     *
125
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
126
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
127
     */
128 4
    protected function requestRaw($endpoint, array $params = [], $method = 'post', array $options = [])
129
    {
130 4
        return $this->request($endpoint, $params, $method, $options, true);
131
    }
132
133
    /**
134
     * Request with SSL.
135
     *
136
     * @param string $endpoint
137
     * @param array  $params
138
     * @param string $method
139
     * @param array  $options
140
     *
141
     * @return \Psr\Http\Message\ResponseInterface|\EasyWeChat\Kernel\Support\Collection|array|object|string
142
     *
143
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
144
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
145
     */
146 1
    protected function safeRequest($endpoint, array $params, $method = 'post', array $options = [])
147
    {
148 1
        $options = array_merge([
149 1
            'cert' => $this->app['config']->get('cert_path'),
150 1
            'ssl_key' => $this->app['config']->get('key_path'),
151
        ], $options);
152
153 1
        return $this->request($endpoint, $params, $method, $options);
154
    }
155
156
    /**
157
     * Wrapping an API endpoint.
158
     *
159
     * @param string $endpoint
160
     *
161
     * @return string
162
     */
163 14
    protected function wrap(string $endpoint): string
164
    {
165 14
        return $this->app->inSandbox() ? "sandboxnew/{$endpoint}" : $endpoint;
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $endpoint instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
166
    }
167
}
168