Reader::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
c 1
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\ReaderException;
10
11
class Reader
12
{
13
    private Config $config;
14
15
    private ?MessageFormatInterface $messageFormat = null;
16
17
    public function __construct(Config $config)
18
    {
19
        $this->config = $config;
20
    }
21
22
    public function readDom(DOMDocument $document): Message
23 4
    {
24
        if ($document->documentElement === null) {
25 4
            throw new ReaderException('Empty document');
26 4
        }
27
28 4
        $xmlNs = $document->documentElement->getAttribute('xmlns');
29
        $this->messageFormat = $this->getMessageFormatForXmlNs($xmlNs);
30 4
31 1
        return $this->messageFormat->getDecoder()->decode($document, $this->config->getXsdValidation());
32
    }
33
34 3
    public function readString(string $string): Message
35 3
    {
36
        $dom = new DOMDocument('1.0', 'UTF-8');
37 2
        $dom->loadXML($string);
38
39
        return $this->readDom($dom);
40 2
    }
41
42 2
    public function readFile(string $file): Message
43 2
    {
44
        if (!file_exists($file)) {
45 2
            throw new ReaderException("{$file} does not exists");
46
        }
47
48 2
        $string = file_get_contents($file);
49
        if ($string === false) {
50 2
            throw new ReaderException("Could not read file {$file}");
51
        }
52
53
        return $this->readString($string);
54 2
    }
55 2
56
    private function getMessageFormatForXmlNs(string $xmlNs): MessageFormatInterface
57
    {
58
        $messageFormats = $this->config->getMessageFormats();
59 2
        foreach ($messageFormats as $messageFormat) {
60
            if ($messageFormat->getXmlNs() === $xmlNs) {
61
                return $messageFormat;
62 3
            }
63
        }
64 3
65 3
        throw new ReaderException("Unsupported format, cannot find message format with xmlns {$xmlNs}");
66 3
    }
67 2
68
    public function getMessageFormat(): ?MessageFormatInterface
69
    {
70
        return $this->messageFormat;
71 1
    }
72
}
73