|
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
|
|
|
|