Passed
Branch master (3c33c7)
by Andrey
04:31
created

XmlErrorParser::parseBody()   A

Complexity

Conditions 6
Paths 32

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 16
c 0
b 0
f 0
nc 32
nop 2
dl 0
loc 29
rs 9.1111
1
<?php
2
namespace Aws\Api\ErrorParser;
3
4
use Aws\Api\Parser\PayloadParserTrait;
5
use Psr\Http\Message\ResponseInterface;
6
7
/**
8
 * Parses XML errors.
9
 */
10
class XmlErrorParser
11
{
12
    use PayloadParserTrait;
0 ignored issues
show
Bug introduced by
The trait Aws\Api\Parser\PayloadParserTrait requires the property $message which is not provided by Aws\Api\ErrorParser\XmlErrorParser.
Loading history...
13
14
    public function __invoke(ResponseInterface $response)
15
    {
16
        $code = (string) $response->getStatusCode();
17
18
        $data = [
19
            'type'        => $code[0] == '4' ? 'client' : 'server',
20
            'request_id'  => null,
21
            'code'        => null,
22
            'message'     => null,
23
            'parsed'      => null
24
        ];
25
26
        $body = $response->getBody();
27
        if ($body->getSize() > 0) {
28
            $this->parseBody($this->parseXml($body), $data);
29
        } else {
30
            $this->parseHeaders($response, $data);
31
        }
32
33
        return $data;
34
    }
35
36
    private function parseHeaders(ResponseInterface $response, array &$data)
37
    {
38
        if ($response->getStatusCode() == '404') {
39
            $data['code'] = 'NotFound';
40
        }
41
42
        $data['message'] = $response->getStatusCode() . ' '
43
            . $response->getReasonPhrase();
44
45
        if ($requestId = $response->getHeaderLine('x-amz-request-id')) {
46
            $data['request_id'] = $requestId;
47
            $data['message'] .= " (Request-ID: $requestId)";
48
        }
49
    }
50
51
    private function parseBody(\SimpleXMLElement $body, array &$data)
52
    {
53
        $data['parsed'] = $body;
54
55
        $namespaces = $body->getDocNamespaces();
56
        if (!isset($namespaces[''])) {
57
            $prefix = '';
58
        } else {
59
            // Account for the default namespace being defined and PHP not
60
            // being able to handle it :(.
61
            $body->registerXPathNamespace('ns', $namespaces['']);
62
            $prefix = 'ns:';
63
        }
64
65
        if ($tempXml = $body->xpath("//{$prefix}Code[1]")) {
66
            $data['code'] = (string) $tempXml[0];
67
        }
68
69
        if ($tempXml = $body->xpath("//{$prefix}Message[1]")) {
70
            $data['message'] = (string) $tempXml[0];
71
        }
72
73
        $tempXml = $body->xpath("//{$prefix}RequestId[1]");
74
        if (empty($tempXml)) {
75
            $tempXml = $body->xpath("//{$prefix}RequestID[1]");
76
        }
77
78
        if (isset($tempXml[0])) {
79
            $data['request_id'] = (string) $tempXml[0];
80
        }
81
    }
82
}
83