ResponseFactory::createFromTransferResponse()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 9
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Skrill\Factory;
6
7
use SimpleXMLElement;
8
use Skrill\Response\Response;
9
use Skrill\Exception\SkrillException;
10
use Psr\Http\Message\ResponseInterface;
11
use Skrill\Exception\SkrillResponseException;
12
13
/**
14
 * Class ResponseFactory.
15
 */
16
final class ResponseFactory
17
{
18
    /**
19
     * @param ResponseInterface $response
20
     *
21
     * @return Response
22
     *
23
     * @throws SkrillException
24
     */
25
    public static function createFromTransferResponse(ResponseInterface $response): Response
26
    {
27
        $xml = self::responseToXML($response);
28
29
        if (!$xml->xpath('transaction[(id) and (amount) and (currency) and (status)]')) {
30
            throw SkrillResponseException::invalidTransactionFormat();
31
        }
32
33
        return new Response((array) $xml->transaction);
34
    }
35
36
    /**
37
     * @param ResponseInterface $response
38
     *
39
     * @return Response
40
     *
41
     * @throws SkrillResponseException
42
     */
43
    public static function createFromRefundResponse(ResponseInterface $response): Response
44
    {
45
        $xml = self::responseToXML($response);
46
47
        if (!$xml->xpath('transaction_id') ||
48
            !$xml->xpath('mb_amount') ||
49
            !$xml->xpath('mb_currency') ||
50
            !$xml->xpath('status')
51
        ) {
52
            throw SkrillResponseException::invalidTransactionFormat();
53
        }
54
55
        return new Response((array) $xml);
56
    }
57
58
    /**
59
     * @param ResponseInterface $response
60
     *
61
     * @return SimpleXMLElement
62
     *
63
     * @throws SkrillResponseException
64
     */
65
    private static function responseToXML(ResponseInterface $response): SimpleXMLElement
66
    {
67
        $xml = new SimpleXMLElement($response->getBody()->getContents());
68
69
        if ($xml->xpath('error/error_msg')) {
70
            throw SkrillResponseException::fromSkillError($xml->error->error_msg);
71
        }
72
73
        return $xml;
74
    }
75
}
76