Failed Conditions
Pull Request — master (#92)
by
unknown
08:11
created

Reader::readDom()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

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