-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXmlHelper.php
More file actions
216 lines (187 loc) · 5.6 KB
/
Copy pathXmlHelper.php
File metadata and controls
216 lines (187 loc) · 5.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
<?php
namespace Drupal\os2forms_fordelingskomponent\Helper;
use Drupal\os2forms_fordelingskomponent\Exception\InvalidXmlException;
use Drupal\os2forms_fordelingskomponent\Settings\HandlerSettings;
use Drupal\webform\WebformSubmissionInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Twig\Environment;
use Twig\TemplateWrapper;
/**
* XML helper.
*/
class XmlHelper {
/**
* Constructor.
*/
public function __construct(
#[Autowire(service: 'twig')]
private readonly Environment $twig,
) {
}
/**
* Wrapper to enable strict variables on the Twig environment.
*
* To not break the Twig instance for others, we restore the strict variables
* state on the instance after running our code.
*
* Important: All code in this class that uses the Twig instance must be run
* with this wrapper.
*/
private function useTwig(callable $callback): mixed {
try {
$strictVariables = $this->twig->isStrictVariables();
$this->twig->enableStrictVariables();
return $callback();
} finally {
if (isset($strictVariables) && $strictVariables) {
$this->twig->enableStrictVariables();
}
else {
$this->twig->disableStrictVariables();
}
}
}
/**
* Render XML template.
*/
public function render(string $template, array $context, bool $validateXml = TRUE): string {
try {
if ($validateXml) {
$this->checkXml($template);
}
$xml = $this->useTwig(
fn () => $this->createTemplate($template)->render($context)
);
// Prettyprint XML.
$dom = new \DOMDocument();
$dom->preserveWhiteSpace = FALSE;
$dom->formatOutput = TRUE;
$dom->loadXML($xml);
return $dom->saveXML();
}
catch (\Throwable $exception) {
throw new InvalidXmlException($exception->getMessage(), $exception->getCode(), $exception);
}
}
/**
* Get render context.
*
* @return array {
* submission: array,
* files: array,
* handler: array{
* settings: array
* }
* }
*/
public function getRenderContext(HandlerSettings $handlerSettings, WebformSubmissionInterface $submission, array $files): array {
return [
'submission' => $submission->toArray(TRUE),
'files' => $files,
'handler' => ['settings' => $handlerSettings->toArray()],
];
}
/**
* Check that Twig template is valid, i.e. has no syntax errors.
*/
public function validateTemplate(string $template): void {
try {
$this->createTemplate($template);
}
catch (\Throwable $exception) {
throw new InvalidXmlException($exception->getMessage(), $exception->getCode(), $exception);
}
}
/**
* Check that XML is valid. Optionally validate using an XSD.
*
* @throws \Drupal\os2forms_fordelingskomponent\Exception\InvalidXmlException
* An exception.
*/
public function validateXml(string $xml, ?string $xsdUrl = NULL, bool $loadXsdContent = FALSE): void {
$this->checkXml($xml);
if (NULL === $xsdUrl) {
return;
}
// https://www.php.net/manual/en/function.libxml-use-internal-errors.php
$useInternalErrors = libxml_use_internal_errors(TRUE);
if ($loadXsdContent) {
$content = file_get_contents($xsdUrl);
if (FALSE === $content) {
throw new InvalidXmlException(sprintf('Error loading XSD: %s', $xsdUrl));
}
}
try {
$reader = new \XMLReader();
$path = tempnam(sys_get_temp_dir(), 'os2forms_fordelingskomponent');
file_put_contents($path, $xml);
$reader->open($path);
$reader->setParserProperty(\XMLReader::VALIDATE, TRUE);
$reader->setSchema($xsdUrl);
$errors = [];
while ($reader->read()) {
if (!$reader->isValid()) {
$error = \libxml_get_last_error();
if ($error instanceof \libXMLError) {
if (!str_contains($error->message, 'no DTD found')) {
$errors[] = $error;
}
}
}
}
if ($errors) {
$message = $this->formatLibXmlErrors($errors);
libxml_clear_errors();
throw new InvalidXmlException('Error validating XML:' . PHP_EOL . $message);
}
} finally {
if (isset($path) && is_file($path)) {
unlink($path);
}
libxml_clear_errors();
libxml_use_internal_errors($useInternalErrors);
}
}
/**
* Check that XML is well-formed.
*/
private function checkXml(string $template): void {
// https://www.php.net/manual/en/function.libxml-use-internal-errors.php
$useInternalErrors = \libxml_use_internal_errors(TRUE);
try {
$doc = new \DomDocument();
if (!$doc->loadXML($template)) {
$message = $this->formatLibXmlErrors(libxml_get_errors());
libxml_clear_errors();
throw new InvalidXmlException('Error loading XML:' . PHP_EOL . $message);
}
}
catch (\Throwable $exception) {
throw new InvalidXmlException($exception->getMessage(), $exception->getCode(), $exception);
} finally {
libxml_use_internal_errors($useInternalErrors);
}
}
/**
* Create a Twig template.
*/
private function createTemplate(string $template): TemplateWrapper {
return $this->useTwig(
fn() => $this->twig->createTemplate($template)
);
}
/**
* Format a list of XML errors.
*/
private function formatLibXmlErrors(array $errors): string {
return implode(
PHP_EOL,
array_unique(
array_map(
static fn (\LibXMLError $error): string => sprintf('%d:%d: %s', $error->line, $error->column, $error->message),
$errors
)
)
);
}
}