Decoder   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Test Coverage

Coverage 95.45%

Importance

Changes 0
Metric Value
eloc 26
dl 0
loc 54
ccs 21
cts 22
cp 0.9545
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A validate() 0 16 3
A decode() 0 18 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Genkgo\Camt;
6
7
use DOMDocument;
8
use Genkgo\Camt\DTO\Message;
9
use Genkgo\Camt\Exception\InvalidMessageException;
10
use SimpleXMLElement;
11
12
class Decoder implements DecoderInterface
13
{
14
    private SimpleXMLElement $document;
15
16
    private Decoder\Message $messageDecoder;
17
18
    /**
19
     * Path to the schema definition.
20
     */
21
    protected string $schemeDefinitionPath;
22
23
    public function __construct(Decoder\Message $messageDecoder, string $schemeDefinitionPath)
24
    {
25
        $this->messageDecoder = $messageDecoder;
26
        $this->schemeDefinitionPath = $schemeDefinitionPath;
27
    }
28
29
    private function validate(DOMDocument $document): void
30
    {
31 23
        libxml_use_internal_errors(true);
32
        $valid = $document->schemaValidate(dirname(__DIR__) . $this->schemeDefinitionPath);
33 23
        $errors = libxml_get_errors();
34 23
        libxml_clear_errors();
35 23
36
        if (!$valid) {
37 22
            $messages = [];
38
            foreach ($errors as $error) {
39 22
                $messages[] = $error->message;
40 22
            }
41 22
42 22
            $errorMessage = implode("\n", $messages);
43
44 22
            throw new InvalidMessageException("Provided XML is not valid according to the XSD:\n{$errorMessage}");
45 1
        }
46 1
    }
47 1
48
    public function decode(DOMDocument $document, bool $xsdValidation = true): Message
49
    {
50 1
        if ($xsdValidation === true) {
51
            $this->validate($document);
52 1
        }
53
54 21
        $document = simplexml_import_dom($document);
55
        if (!$document) {
56 23
            throw new InvalidMessageException('Provided XML could not be parsed');
57
        }
58 23
59 22
        $this->document = $document;
60
61
        $message = new DTO\Message();
62 22
        $this->messageDecoder->addGroupHeader($message, $this->document);
63 22
        $this->messageDecoder->addRecords($message, $this->document);
64
65
        return $message;
66
    }
67
}
68