Completed
Push — master ( a4151f...f7c7ac )
by Frederik
03:04
created

Reader::getMessageFormatForXmlNs()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 1
dl 0
loc 11
ccs 6
cts 6
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
1
<?php
2
namespace Genkgo\Camt;
3
4
use DOMDocument;
5
use Genkgo\Camt\DTO\Message;
6
use Genkgo\Camt\Exception\ReaderException;
7
8
/**
9
 * Class Reader
10
 * @package Genkgo\Camt
11
 */
12
class Reader
13
{
14
    /**
15
     * @var Config
16
     */
17
    private $config;
18
19
    /**
20
     * @param Config $config
21
     */
22 3
    public function __construct(Config $config)
23
    {
24 3
        $this->config = $config;
25 3
    }
26
27
    /**
28
     * @param DOMDocument $document
29
     * @return mixed
30
     * @throws ReaderException
31
     */
32 3
    public function readDom(DOMDocument $document)
33
    {
34 3
        if ($document->documentElement === null) {
35 1
            throw new ReaderException("Empty document");
36
        }
37
38 2
        $xmlNs = $document->documentElement->getAttribute('xmlns');
39 2
        $messageFormat = $this->getMessageFormatForXmlNs($xmlNs);
40
41 1
        return $messageFormat->getDecoder()->decode($document);
42
    }
43
44
    /**
45
     * @param $string
46
     * @return mixed
47
     * @throws ReaderException
48
     */
49 1
    public function readString($string)
50
    {
51 1
        $dom = new DOMDocument('1.0', 'UTF-8');
52 1
        $dom->loadXML($string);
53
54 1
        return $this->readDom($dom);
55
    }
56
57
    public function readDoc($string)
58
    {
59
        $string = file_get_contents($string);
60
        $dom = new DOMDocument('1.0', 'UTF-8');
61
        $dom->loadXML($string);
62
63
        return $dom;
64
    }
65
66
67
    /**
68
     * @param  string $file
69
     * @return mixed|Message
70
     * @throws ReaderException
71
     */
72 1
    public function readFile($file)
73
    {
74 1
        if (!file_exists($file)) {
75
            throw new ReaderException("{$file} does not exists");
76
        }
77
78 1
        return $this->readString(file_get_contents($file));
79
    }
80
81
    /**
82
     * @param $xmlNs
83
     * @return MessageFormatInterface
84
     * @throws ReaderException
85
     */
86 2
    private function getMessageFormatForXmlNs($xmlNs)
87
    {
88 2
        $messageFormats = $this->config->getMessageFormats();
89 2
        foreach ($messageFormats as $messageFormat) {
90 2
            if ($messageFormat->getXmlNs() === $xmlNs) {
91 1
                return $messageFormat;
92
            }
93
        }
94
95 1
        throw new ReaderException("Unsupported format, cannot find message format with xmlns {$xmlNs}");
96
    }
97
}
98