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