Passed
Pull Request — master (#23)
by
unknown
10:02 queued 05:04
created

Guzzle::createAfterPayApiResponseErrorTransfer()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 1
dl 0
loc 13
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * MIT License
5
 * For full license information, please view the LICENSE file that was distributed with this source code.
6
 */
7
8
namespace SprykerEco\Zed\AfterPay\Business\Api\Adapter\Client\Http;
9
10
use Generated\Shared\Transfer\AfterPayApiResponseErrorTransfer;
0 ignored issues
show
Bug introduced by
The type Generated\Shared\Transfe...piResponseErrorTransfer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use GuzzleHttp\Client;
12
use GuzzleHttp\Exception\RequestException;
13
use GuzzleHttp\Psr7\Request;
14
use Psr\Http\Message\RequestInterface;
15
use Psr\Http\Message\ResponseInterface;
16
use Psr\Http\Message\StreamInterface;
17
use SprykerEco\Zed\AfterPay\AfterPayConfig;
18
use SprykerEco\Zed\AfterPay\Business\Api\Adapter\Client\ClientInterface;
19
use SprykerEco\Zed\AfterPay\Business\Exception\ApiHttpRequestException;
20
use SprykerEco\Zed\AfterPay\Dependency\Service\AfterPayToUtilEncodingServiceInterface;
21
22
class Guzzle implements ClientInterface
23
{
24
    public const REQUEST_METHOD_POST = 'POST';
25
    public const REQUEST_METHOD_GET = 'GET';
26
27
    public const REQUEST_HEADER_X_AUTH_KEY = 'X-Auth-Key';
28
    public const REQUEST_HEADER_CONTENT_TYPE = 'Content-Type';
29
30
    public const HEADER_CONTENT_TYPE_JSON = 'application/json';
31
32
    /**
33
     * @var \SprykerEco\Zed\AfterPay\Dependency\Service\AfterPayToUtilEncodingServiceInterface
34
     */
35
    protected $encodingService;
36
37
    /**
38
     * @var \GuzzleHttp\ClientInterface
39
     */
40
    protected $client;
41
42
    /**
43
     * @var \SprykerEco\Zed\AfterPay\AfterPayConfig
44
     */
45
    protected $config;
46
47
    /**
48
     * @param \SprykerEco\Zed\AfterPay\Dependency\Service\AfterPayToUtilEncodingServiceInterface $encodingService
49
     * @param \SprykerEco\Zed\AfterPay\AfterPayConfig $config
50
     */
51
    public function __construct(
52
        AfterPayToUtilEncodingServiceInterface $encodingService,
53
        AfterPayConfig $config
54
    ) {
55
        $this->encodingService = $encodingService;
56
        $this->config = $config;
57
        $this->client = new Client();
58
    }
59
60
    /**
61
     * @param string $endPointUrl
62
     * @param string|null $jsonBody
63
     *
64
     * @return \Psr\Http\Message\StreamInterface
65
     */
66
    public function sendPost(string $endPointUrl, ?string $jsonBody = null): StreamInterface
67
    {
68
        $postRequest = $this->buildPostRequest($endPointUrl, $jsonBody);
69
        $response = $this->send($postRequest);
70
71
        return $response->getBody();
72
    }
73
74
    /**
75
     * @param string $endPointUrl
76
     *
77
     * @return string
78
     */
79
    public function sendGet(string $endPointUrl): string
80
    {
81
        $getRequest = $this->buildGetRequest($endPointUrl);
82
        $response = $this->send($getRequest);
83
84
        return $response->getBody()->getContents();
85
    }
86
87
    /**
88
     * @param string $endPointUrl
89
     *
90
     * @return int
91
     */
92
    public function getStatus(string $endPointUrl): int
93
    {
94
        $getRequest = $this->buildGetRequest($endPointUrl);
95
        $response = $this->send($getRequest);
96
97
        return $response->getStatusCode();
98
    }
99
100
    /**
101
     * @param \Psr\Http\Message\RequestInterface $request
102
     * @param array $options
103
     *
104
     * @throws \SprykerEco\Zed\AfterPay\Business\Exception\ApiHttpRequestException
105
     *
106
     * @return \Psr\Http\Message\ResponseInterface
107
     */
108
    protected function send(RequestInterface $request, array $options = []): ResponseInterface
109
    {
110
        try {
111
            return $this->client->send($request, $options);
112
        } catch (RequestException $requestException) {
113
            $apiHttpRequestException = new ApiHttpRequestException($requestException->getMessage());
114
115
            $responseContent = $this->getExceptionResponseContent($requestException);
116
            $errorsResponseData = $this->encodingService->decodeJson($responseContent, true);
117
            $afterPayApiResponseErrorTransfer = $this->createAfterPayApiResponseErrorTransfer($errorsResponseData);
118
119
            if (!empty($afterPayApiResponseErrorTransfer)) {
120
                $apiHttpRequestException->setError($afterPayApiResponseErrorTransfer);
121
                $apiHttpRequestException->setDetailedMessage($responseContent);
122
            }
123
124
            throw $apiHttpRequestException;
125
        }
126
    }
127
128
    protected function createAfterPayApiResponseErrorTransfer(?array $errorsResponseData): ?AfterPayApiResponseErrorTransfer
0 ignored issues
show
Unused Code introduced by
The parameter $errorsResponseData is not used and could be removed. ( Ignorable by Annotation )

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

128
    protected function createAfterPayApiResponseErrorTransfer(/** @scrutinizer ignore-unused */ ?array $errorsResponseData): ?AfterPayApiResponseErrorTransfer

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
129
    {
130
        if (empty($errorResponseData[0])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $errorResponseData does not exist. Did you maybe mean $errorsResponseData?
Loading history...
131
            return null;
132
        }
133
134
        $errorDetails = $errorResponseData[0];
135
        return (new AfterPayApiResponseErrorTransfer())
136
            ->setActionCode($errorDetails['actionCode'])
137
            ->setCode($errorDetails['code'])
138
            ->setType($errorDetails['type'])
139
            ->setMessage($errorDetails['message'])
140
            ->setIsSuccess(false);
141
    }
142
143
    protected function getExceptionResponseContent(RequestException $requestException): string
144
    {
145
        $response = $requestException->getResponse();
146
        return $response instanceof ResponseInterface ? $response->getBody()->getContents() : '';
147
    }
148
149
    /**
150
     * @param string $endPointUrl
151
     * @param string|null $jsonBody
152
     *
153
     * @return \Psr\Http\Message\RequestInterface
154
     */
155
    protected function buildPostRequest(string $endPointUrl, ?string $jsonBody = null): RequestInterface
156
    {
157
        return new Request(
158
            static::REQUEST_METHOD_POST,
159
            $endPointUrl,
160
            [
161
                (string)static::REQUEST_HEADER_CONTENT_TYPE => (string)static::HEADER_CONTENT_TYPE_JSON,
162
                (string)static::REQUEST_HEADER_X_AUTH_KEY => (string)$this->config->getApiCredentialsAuthKey(),
163
            ],
164
            $jsonBody
165
        );
166
    }
167
168
    /**
169
     * @param string $endPointUrl
170
     *
171
     * @return \Psr\Http\Message\RequestInterface
172
     */
173
    protected function buildGetRequest(string $endPointUrl): RequestInterface
174
    {
175
        return new Request(
176
            static::REQUEST_METHOD_GET,
177
            $endPointUrl,
178
            [
179
                (string)static::REQUEST_HEADER_CONTENT_TYPE => (string)static::HEADER_CONTENT_TYPE_JSON,
180
                (string)static::REQUEST_HEADER_X_AUTH_KEY => (string)$this->config->getApiCredentialsAuthKey(),
181
            ]
182
        );
183
    }
184
}
185