Completed
Push — master ( 356caf...e5e6b5 )
by Carlos
09:26
created

BaseClient::logMiddleware()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 5
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
    public function __construct(Application $app)
41
    {
42
        $this->app = $app;
43
44
        $this->setHttpClient($this->app['http_client']);
45
    }
46
47
    /**
48
     * Extra request params.
49
     *
50
     * @return array
51
     */
52
    protected function prepends()
53
    {
54
        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
    protected function request(string $endpoint, array $params = [], $method = 'post', array $options = [], $returnResponse = false)
72
    {
73
        $base = [
74
            'mch_id' => $this->app['config']['mch_id'],
75
            'nonce_str' => uniqid(),
76
            'sub_mch_id' => $this->app['config']['sub_mch_id'],
77
            'sub_appid' => $this->app['config']['sub_appid'],
78
        ];
79
80
        $params = array_filter(array_merge($base, $this->prepends(), $params));
81
82
        $params['sign'] = Support\generate_sign($params, $this->app->getKey($endpoint));
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

82
        $params['sign'] = /** @scrutinizer ignore-call */ Support\generate_sign($params, $this->app->getKey($endpoint));
Loading history...
83
        $options = array_merge([
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 8 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
84
            'body' => Support\XML::build($params),
85
        ], $options);
86
87
        $this->pushMiddleware($this->logMiddleware(), 'log');
88
89
        $response = $this->performRequest($endpoint, $method, $options);
90
91
        return $returnResponse ? $response : $this->castResponseToType($response, $this->app->config->get('response_type'));
92
    }
93
94
    /**
95
     * Log the request.
96
     *
97
     * @return \Closure
98
     */
99
    protected function logMiddleware()
100
    {
101
        $formatter = new MessageFormatter($this->app['config']['http.log_template'] ?? MessageFormatter::DEBUG);
102
103
        return Middleware::log($this->app['logger'], $formatter);
104
    }
105
106
    /**
107
     * Make a request and return raw response.
108
     *
109
     * @param string $endpoint
110
     * @param array  $params
111
     * @param string $method
112
     * @param array  $options
113
     *
114
     * @return ResponseInterface
115
     *
116
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
117
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
118
     */
119
    protected function requestRaw($endpoint, array $params = [], $method = 'post', array $options = [])
120
    {
121
        return $this->request($endpoint, $params, $method, $options, true);
122
    }
123
124
    /**
125
     * Request with SSL.
126
     *
127
     * @param string $endpoint
128
     * @param array  $params
129
     * @param string $method
130
     * @param array  $options
131
     *
132
     * @return \Psr\Http\Message\ResponseInterface|\EasyWeChat\Kernel\Support\Collection|array|object|string
133
     *
134
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
135
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
136
     */
137
    protected function safeRequest($endpoint, array $params, $method = 'post', array $options = [])
138
    {
139
        $options = array_merge([
140
            'cert' => $this->app['config']->get('cert_path'),
141
            'ssl_key' => $this->app['config']->get('key_path'),
142
        ], $options);
143
144
        return $this->request($endpoint, $params, $method, $options);
145
    }
146
147
    /**
148
     * Wrapping an API endpoint.
149
     *
150
     * @param string $endpoint
151
     *
152
     * @return string
153
     */
154
    protected function wrap(string $endpoint): string
155
    {
156
        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...
157
    }
158
}
159