Passed
Push — master ( 0ba60b...5c85fa )
by Roman
07:58
created

SkrillClient::viewHistory()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 76
Code Lines 53

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 53
c 1
b 0
f 0
dl 0
loc 76
rs 8.7143
cc 5
nc 8
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Skrill;
6
7
use ArrayObject;
8
use LimitIterator;
9
use SplFileObject;
10
use DateTimeImmutable;
11
use DateTimeInterface;
12
use Skrill\ValueObject\Sid;
13
use Skrill\ValueObject\Url;
14
use Skrill\ValueObject\Email;
15
use Skrill\Response\Response;
16
use Skrill\Factory\SidFactory;
17
use GuzzleHttp\RequestOptions;
18
use GuzzleHttp\ClientInterface;
19
use Skrill\Request\SaleRequest;
20
use Skrill\Response\HistoryItem;
21
use Skrill\ValueObject\Password;
22
use Skrill\Request\PayoutRequest;
23
use Skrill\Request\RefundRequest;
24
use Skrill\Request\TransferRequest;
25
use Skrill\Factory\ResponseFactory;
26
use Skrill\Request\OnDemandRequest;
27
use Skrill\ValueObject\CompanyName;
28
use Psr\Http\Message\ResponseInterface;
29
use GuzzleHttp\Exception\GuzzleException;
30
use Skrill\Exception\SkrillResponseException;
31
32
/**
33
 * Skrill HTTP client.
34
 */
35
final class SkrillClient implements
36
    SkrillHistoryClientInterface,
37
    SkrillOnDemandClientInterface,
38
    SkrillSaleClientInterface,
39
    SkrillTransferClientInterface,
40
    SkrillRefundClientInterface,
41
    SkrillPayoutClientInterface
42
{
43
    /**
44
     * @var ClientInterface
45
     */
46
    private $client;
47
48
    /**
49
     * A description to be shown on the Skrill payment page in the logo area if there is no logo_url parameter.
50
     *
51
     * recipient_description
52
     *
53
     * @var CompanyName|null
54
     */
55
    private $companyName;
56
57
    /**
58
     * Email address of your Skrill merchant account.
59
     *
60
     * pay_to_email
61
     *
62
     * @var Email
63
     */
64
    private $merchantEmail;
65
66
    /**
67
     * The URL of the logo which you would like to appear in the top right of the Skrill page.
68
     *
69
     * logo_url
70
     *
71
     * @var Url|null
72
     */
73
    private $logoUrl;
74
75
    /**
76
     * Skrill API/MQI password.
77
     *
78
     * @var string
79
     */
80
    private $password;
81
82
    /**
83
     * @param ClientInterface  $client
84
     * @param Email            $merchantEmail
85
     * @param Password         $password
86
     * @param Url|null         $logoUrl
87
     * @param CompanyName|null $companyName
88
     */
89
    public function __construct(
90
        ClientInterface $client,
91
        Email $merchantEmail,
92
        Password $password,
93
        Url $logoUrl = null,
94
        CompanyName $companyName = null
95
    ) {
96
        $this->client = $client;
97
        $this->companyName = $companyName;
98
        $this->merchantEmail = $merchantEmail;
99
        $this->logoUrl = $logoUrl;
100
        $this->password = md5(strval($password));
101
    }
102
103
    /**
104
     * {@inheritdoc}
105
     *
106
     * @throws GuzzleException
107
     */
108
    public function prepareSale(SaleRequest $request): Sid
109
    {
110
        $params = $request->getPayload();
111
        $params['prepare_only'] = 1; // Forces only the SID to be returned without the actual page.
112
        $params['pay_to_email'] = strval($this->merchantEmail);
113
114
        if (null != $this->logoUrl) {
115
            $params['logo_url'] = strval($this->logoUrl);
116
        }
117
118
        if (null != $this->companyName) {
119
            $params['recipient_description'] = strval($this->companyName);
120
        }
121
122
        return SidFactory::createFromSaleResponse(
123
            $this->request($params, 'https://pay.skrill.com')
124
        );
125
    }
126
127
    /**
128
     * {@inheritdoc}
129
     *
130
     * @throws GuzzleException
131
     */
132
    public function prepareTransfer(TransferRequest $request): Sid
133
    {
134
        $params = $request->getPayload();
135
        $params['action'] = 'prepare';
136
        $params['email'] = strval($this->merchantEmail);
137
        $params['password'] = $this->password;
138
139
        return SidFactory::createFromXMLResponse(
140
            $this->request($params, 'https://www.skrill.com/app/pay.pl')
141
        );
142
    }
143
144
    /**
145
     * {@inheritdoc}
146
     *
147
     * @throws GuzzleException
148
     */
149
    public function preparePayout(PayoutRequest $request): Sid
150
    {
151
        $params = $request->getPayload();
152
        $params['action'] = 'prepare';
153
        $params['email'] = strval($this->merchantEmail);
154
        $params['password'] = $this->password;
155
156
        return SidFactory::createFromXMLResponse(
157
            $this->request($params, 'https://www.skrill.com/app/pay.pl')
158
        );
159
    }
160
161
    /**
162
     * {@inheritdoc}
163
     *
164
     * @throws GuzzleException
165
     */
166
    public function prepareRefund(RefundRequest $request): Sid
167
    {
168
        $params = $request->getPayload();
169
        $params['action'] = 'prepare';
170
        $params['email'] = strval($this->merchantEmail);
171
        $params['password'] = $this->password;
172
173
        return SidFactory::createFromXMLResponse(
174
            $this->request($params, 'https://www.skrill.com/app/refund.pl')
175
        );
176
    }
177
178
    /**
179
     * {@inheritdoc}
180
     *
181
     * @throws GuzzleException
182
     */
183
    public function executeTransfer(Sid $sid): Response
184
    {
185
        return ResponseFactory::createFromTransferResponse(
186
            $this->request(['action' => 'transfer', 'sid' => strval($sid)], 'https://www.skrill.com/app/pay.pl')
187
        );
188
    }
189
190
    /**
191
     * {@inheritdoc}
192
     *
193
     * @throws GuzzleException
194
     */
195
    public function executePayout(Sid $sid): Response
196
    {
197
        return ResponseFactory::createFromTransferResponse(
198
            $this->request(['action' => 'transfer', 'sid' => strval($sid)], 'https://www.skrill.com/app/pay.pl')
199
        );
200
    }
201
202
    /**
203
     * {@inheritdoc}
204
     *
205
     * @throws GuzzleException
206
     */
207
    public function executeRefund(Sid $sid): Response
208
    {
209
        return ResponseFactory::createFromRefundResponse(
210
            $this->request(['action' => 'refund', 'sid' => strval($sid)], 'https://www.skrill.com/app/refund.pl')
211
        );
212
    }
213
214
    /**
215
     * {@inheritdoc}
216
     *
217
     * @throws GuzzleException
218
     */
219
    public function prepareOnDemand(OnDemandRequest $request): Sid
220
    {
221
        $params = $request->getPayload();
222
        $params['action'] = 'prepare';
223
        $params['email'] = strval($this->merchantEmail);
224
        $params['password'] = $this->password;
225
226
        return SidFactory::createFromXMLResponse(
227
            $this->request($params, 'https://www.skrill.com/app/ondemand_request.pl')
228
        );
229
    }
230
231
    /**
232
     * {@inheritdoc}
233
     *
234
     * @throws GuzzleException
235
     */
236
    public function executeOnDemand(Sid $sid): Response
237
    {
238
        return ResponseFactory::createFromTransferResponse(
239
            $this->request(
240
                ['action' => 'request', 'sid' => strval($sid)],
241
                'https://www.skrill.com/app/ondemand_request.pl'
242
            )
243
        );
244
    }
245
246
    /**
247
     * {@inheritdoc}
248
     *
249
     * @throws GuzzleException
250
     */
251
    public function viewHistory(DateTimeInterface $startDate, DateTimeInterface $endDate = null): ArrayObject
252
    {
253
        $params = [
254
            'email' => strval($this->merchantEmail),
255
            'password' => $this->password,
256
            'action' => 'history',
257
            'start_date' => $startDate->format('d-m-Y'),
258
        ];
259
260
        if (null != $endDate) {
261
            $params['end_date'] = $endDate->format('d-m-y');
262
        }
263
264
        $tmpFile = new SplFileObject(tempnam(sys_get_temp_dir(), strval(rand())), 'w+');
265
        $this->client->request(
266
            'POST',
267
            'https://www.skrill.com/app/query.pl',
268
            [
269
                RequestOptions::FORM_PARAMS => $params,
270
                RequestOptions::SINK => $tmpFile->getPathname(),
271
            ]
272
        );
273
274
        if (preg_match('/^[\d]{3}[\t]{2}(.+)$/', $tmpFile->current(), $matches)) {
275
            throw SkrillResponseException::fromSkillError($matches[1]);
276
        }
277
278
        $result = new ArrayObject();
279
        $tmpFile->rewind();
280
        $tmpFile->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY);
281
282
        foreach (new LimitIterator($tmpFile, 1) as $row) {
283
            [
284
                ,
285
                $time,
286
                $type,
287
                $details,
288
                $lesion,
289
                $profit,
290
                $status,
291
                $balance,
292
                $reference,
293
                $amount,
294
                $currency,
295
                $info,
296
                $skrillId,
297
                $paymentType,
298
            ] = $row;
299
            $datetime = DateTimeImmutable::createFromFormat('d M y H:i', $time);
300
301
            if (!$datetime instanceof DateTimeImmutable) {
302
                throw SkrillResponseException::fromSkillError(sprintf('Invalid time "%s".', $time));
303
            }
304
305
            $result->append(
306
                new HistoryItem(
307
                    $reference,
308
                    $skrillId,
309
                    $datetime,
310
                    $type,
311
                    $details,
312
                    $lesion,
313
                    $profit,
314
                    $status,
315
                    $balance,
316
                    $amount,
317
                    $currency,
318
                    $info,
319
                    $paymentType
320
                )
321
            );
322
        }
323
324
        unlink($tmpFile->getPathname());
325
326
        return $result;
327
    }
328
329
    /**
330
     * @param array  $parameters
331
     * @param string $url
332
     *
333
     * @return ResponseInterface
334
     *
335
     * @throws GuzzleException
336
     */
337
    private function request(array $parameters, string $url): ResponseInterface
338
    {
339
        return $this->client->request(
340
            'POST',
341
            $url,
342
            [
343
                RequestOptions::FORM_PARAMS => $parameters,
344
                RequestOptions::HEADERS => [
345
                    'Accept' => 'text/xml',
346
                ],
347
            ]
348
        );
349
    }
350
}
351