Completed
Pull Request — master (#16)
by Alessandro
06:12
created

XmlLoadException::decodeXmlError()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 0
cts 22
cp 0
rs 9.1608
c 0
b 0
f 0
cc 5
nc 8
nop 2
crap 30
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Fazland\SkebbyRestClient\Exception;
6
7
use LibXMLError;
8
9
use function sprintf;
10
use function trim;
11
12
use const LIBXML_ERR_ERROR;
13
use const LIBXML_ERR_FATAL;
14
use const LIBXML_ERR_WARNING;
15
16
/**
17
 * Represents an exception thrown on XML load.
18
 */
19
class XmlLoadException extends Exception
20
{
21
    private string $response;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_STRING, expecting T_FUNCTION or T_CONST
Loading history...
22
23
    /**
24
     * @param LibXMLError[] $errors
25
     */
26
    public function __construct(string $response, array $errors)
27
    {
28
        parent::__construct();
29
30
        $this->response = $response;
31
        $this->message = '';
32
33
        foreach ($errors as $error) {
34
            $this->message .= $this->decodeXmlError($error, $response);
35
        }
36
    }
37
38
    public function __toString(): string
39
    {
40
        return '[' . static::class . '] ' . $this->message . "\n" .
41
            'Response: ' . "\n" .
42
            $this->response;
43
    }
44
45
    private function decodeXmlError(LibXMLError $error, string $xml): string
46
    {
47
        $return = $xml[$error->line - 1] . "\n";
48
49
        switch ($error->level) {
50
            case LIBXML_ERR_WARNING:
51
                $return .= sprintf('Warning %u: ', $error->code);
52
                break;
53
54
            case LIBXML_ERR_ERROR:
55
                $return .= sprintf('Error %u: ', $error->code);
56
                break;
57
58
            case LIBXML_ERR_FATAL:
59
                $return .= sprintf('Fatal Error %u: ', $error->code);
60
                break;
61
        }
62
63
        $return .= sprintf("%s\n  Line: %u\n  Column: %u ", trim($error->message), $error->line, $error->column);
64
        if ($error->file) {
65
            $return .= sprintf("\n  File: %s", $error->file);
66
        }
67
68
        return $return . "\n\n";
69
    }
70
}
71