Decoder::decode()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3.0123

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 4
nop 2
dl 0
loc 18
ccs 8
cts 9
cp 0.8889
crap 3.0123
rs 9.9332
c 0
b 0
f 0
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