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

XmlLoadException   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 69
Duplicated Lines 10.14 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 1
dl 7
loc 69
ccs 0
cts 37
cp 0
rs 10
c 0
b 0
f 0

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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