Test Failed
Push — develop ( 7f7300...ab10e8 )
by Hirofumi
04:25 queued 01:38
created

Client::setRequestParamsForGetRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
nc 1
cc 1
eloc 3
nop 2
1
<?php
2
3
namespace Shippinno\YahooShoppingJp;
4
5
use GuzzleHttp\Client as HttpClient;
6
use GuzzleHttp\Exception\ConnectException as GuzzleConnectException;
7
use GuzzleHttp\Exception\ServerException as GuzzleServerException;
8
use GuzzleHttp\Exception\ClientException as GuzzleClientException;
9
use GuzzleHttp\RequestOptions;
10
use Psr\Http\Message\ResponseInterface;
11
use Shippinno\YahooShoppingJp\Api\AbstractApi;
12
use Shippinno\YahooShoppingJp\Exception\ClientException;
13
use Shippinno\YahooShoppingJp\Exception\ConnectException;
14
use Shippinno\YahooShoppingJp\Exception\ExpiredAccessTokenException;
15
use Shippinno\YahooShoppingJp\Exception\ServerException;
16
use Shippinno\YahooShoppingJp\Request\AbstractRequest;
17
use SoapBox\Formatter\Formatter;
18
19
class Client
20
{
21
    /**
22
     * @var string
23
     */
24
    private $baseUrl = 'https://circus.shopping.yahooapis.jp/ShoppingWebService/V1/';
25
26
    /**
27
     * @var HttpClient
28
     */
29
    private $httpClient;
30
31
    /**
32
     * @var AbstractApi
33
     */
34
    private $api;
35
36
    /**
37
     * @var string
38
     */
39
    private $accessToken;
40
41
    /**
42
     * @var string
43
     */
44
    private $cert;
45
46
    /**
47
     * @var
48
     */
49
    private $sslKey;
50
51
    /**
52
     * @param string $accessToken
53
     * @param string|null $cert
54
     * @param string|null $sslKey
55
     * @param bool $enableTestMode
56
     * @param HttpClient|null $httpClient
57
     */
58
    public function __construct(
59
        string $accessToken,
60
        string $cert = null,
61
        string $sslKey = null,
62
        bool $enableTestMode = false,
63
        HttpClient $httpClient = null
64
    ) {
65
        if ($enableTestMode) {
66
            $this->baseUrl = 'https://test.circus.shopping.yahooapis.jp/ShoppingWebService/V1/';
67
        }
68
69
        if (null === $httpClient) {
70
            $httpClient = new HttpClient([
71
                'base_uri' => $this->baseUrl,
72
            ]);
73
        }
74
75
        $this->accessToken = $accessToken;
76
        $this->cert = $cert;
77
        $this->sslKey = $sslKey;
78
        $this->httpClient = $httpClient;
79
    }
80
81
    /**
82
     * @param AbstractRequest $request
83
     * @return array|mixed
84
     * @throws ClientException
85
     * @throws ConnectException
86
     * @throws ExpiredAccessTokenException
87
     * @throws ServerException
88
     */
89
    public function execute(AbstractRequest $request): array
90
    {
91
        $this->setApi($request->api());
92
93
        $options = $this->setAuthorizationHeader($this->setRequestParams($request));
94
95
        $options = $this->setCertAndSslKey($options);
96
97
        try {
98
            $rawResponse = $this->request($options);
99
        } catch (GuzzleClientException $e) {
100
            $wwwAuthenticateHeaders = $e->getResponse()->getHeader('WWW-Authenticate');
101
102
            if ([] !== $wwwAuthenticateHeaders) {
103
                if (false !== strpos($wwwAuthenticateHeaders[0], 'error_description="expired token"')) {
104
                    throw new ExpiredAccessTokenException;
105
                }
106
            }
107
108
            throw new ClientException($e->getMessage(), $e->getCode(), $e);
109
        } catch (GuzzleServerException $e) {
110
            throw new ServerException($e->getMessage(), $e->getCode(), $e);
111
        } catch (GuzzleConnectException $e) {
112
            throw new ConnectException($e->getMessage(), $e->getCode(), $e);
113
        }
114
115
        return $this->api->distillResponse($this->decodeResponse($rawResponse));
116
//        $response = $request->response()->setData($distilledResponse);
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
117
    }
118
119
    /**
120
     * @param AbstractApi $api
121
     */
122
    private function setApi(AbstractApi $api)
123
    {
124
        $this->api = $api;
125
    }
126
127
    /**
128
     * @param array $options
129
     * @return array
130
     */
131
    private function setCertAndSslKey(array $options): array
132
    {
133
        if (null !== $this->cert && null !== $this->sslKey) {
134
            $options[RequestOptions::CERT] = $this->cert;
135
            $options[RequestOptions::SSL_KEY] = $this->sslKey;
136
        }
137
138
        return $options;
139
    }
140
141
    /**
142
     * @param array $options
143
     * @return array
144
     */
145
    private function setAuthorizationHeader(array $options): array
146
    {
147
        $options['headers'] = [
148
            'Authorization' => 'Bearer ' . $this->accessToken,
149
        ];
150
151
        return $options;
152
    }
153
154
    /**
155
     * @param AbstractRequest $request
156
     * @return array
157
     */
158
    private function setRequestParams(AbstractRequest $request): array
159
    {
160
        $options = [];
161
        if ($this->api->httpMethod()->equals(HttpMethod::GET())) {
162
            $options = $this->setRequestParamsForGetRequest($options, $request);
163
        } else {
164
            if ($this->api->httpMethod()->equals(HttpMethod::POST())) {
165
                $options = $this->setRequestParamsForPostRequest($options, $request);
166
            }
167
        }
168
169
        return $options;
170
    }
171
172
    /**
173
     * @param array $options
174
     * @param AbstractRequest $request
175
     * @return array
176
     */
177
    private function setRequestParamsForGetRequest(array $options, AbstractRequest $request): array
178
    {
179
        $options['query'] = $request->getParams();
180
181
        return $options;
182
    }
183
184
    /**
185
     * @param array $options
186
     * @param AbstractRequest $request
187
     * @return array
188
     */
189
    private function setRequestParamsForPostRequest(array $options, AbstractRequest $request): array
190
    {
191
        if ($this->api->expectsFormFields()) {
192
            $options['form_params'] = $request->getParams();
193
        } else {
194
            $options['body'] = $request->getParams();
195
        }
196
197
        return $options;
198
    }
199
200
201
    /**
202
     * @param $options
203
     * @return mixed|ResponseInterface
204
     */
205
    private function request($options)
206
    {
207
        return $this->httpClient->request(
208
            $this->api->httpMethod()->getValue(),
209
            $this->api->path(),
210
            $options
211
        );
212
    }
213
214
    /**
215
     * @param ResponseInterface $rawResponse
216
     * @return array
217
     */
218
    private function decodeResponse(ResponseInterface $rawResponse): array
219
    {
220
        $formatter = Formatter::make($rawResponse->getBody()->getContents(), Formatter::XML);
221
        return $formatter->toArray();
222
    }
223
}
224