Completed
Pull Request — master (#13)
by Yann
03:10
created

Reader   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 95.65%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
wmc 9
c 3
b 0
f 1
lcom 1
cbo 4
dl 0
loc 74
ccs 22
cts 23
cp 0.9565
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A readDom() 0 10 2
A readString() 0 6 1
A readFile() 0 8 2
A getMessageFormatForXmlNs() 0 11 3
1
<?php
2
namespace Genkgo\Camt;
3
4
use DOMDocument;
5
use Genkgo\Camt\Exception\ReaderException;
6
use Genkgo\Camt\Camt053\Message;
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|Message
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 1
        return $messageFormat->getDecoder()->decode($document);
41
    }
42
43
    /**
44
     * @param $string
45
     * @return mixed|Message
46
     * @throws ReaderException
47
     */
48 1
    public function readString($string)
49
    {
50 1
        $dom = new DOMDocument('1.0', 'UTF-8');
51 1
        $dom->loadXML($string);
52 1
        return $this->readDom($dom);
53
    }
54
55
    /**
56
     * @param $file
57
     * @return mixed|Message
58
     * @throws ReaderException
59
     */
60 1
    public function readFile($file)
61
    {
62 1
        if (!file_exists($file)) {
63
            throw new ReaderException("{$file} does not exists");
64
        }
65
66 1
        return $this->readString(file_get_contents($file));
67
    }
68
69
    /**
70
     * @param $xmlNs
71
     * @return MessageFormatInterface
72
     * @throws ReaderException
73
     */
74 2
    private function getMessageFormatForXmlNs($xmlNs)
75
    {
76 2
        $messageFormats = $this->config->getMessageFormats();
77 2
        foreach ($messageFormats as $messageFormat) {
78 2
            if ($messageFormat->getXmlNs() === $xmlNs) {
79 2
                return $messageFormat;
80
            }
81
        }
82
83 1
        throw new ReaderException("Unsupported format, cannot find message format with xmlns {$xmlNs}");
84
    }
85
}
86