Skip to content

Commit 5ca3fa9

Browse files
committed
Added os2forms_fordelingskomponent_xml_encode Twig filter
1 parent c852c7f commit 5ca3fa9

2 files changed

Lines changed: 66 additions & 0 deletions

File tree

docs/Users-manual.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,3 +262,28 @@ float value based on a language code:
262262
{{ os2forms_fordelingskomponent_floatval('1,23', langcode: 'da') == 1.23 }}
263263
{{ os2forms_fordelingskomponent_floatval('1.23', langcode: 'da') == 123}}
264264
```
265+
266+
A Twig filter, `os2forms_fordelingskomponent_xml_encode`, can be used to convert an array value to an XML fragment:
267+
268+
``` twig
269+
{% set value = {
270+
Person: {
271+
firstname: 'Lucky',
272+
lastname: 'Luke',
273+
},
274+
Horse: {
275+
name: 'Jolly Jumper',
276+
},
277+
} %}
278+
{{ value|os2forms_fordelingskomponent_xml_encode }}
279+
```
280+
281+
will render
282+
283+
``` xml
284+
<Person><firstname>John</firstname><lastname>Doe</lastname></Person><Horse><name>Jolly Jumper</name></Horse>
285+
```
286+
287+
Notice that `os2forms_fordelingskomponent_xml_encode` is "[safe for
288+
HTML](https://twig.symfony.com/doc/3.x/advanced.html#automatic-escaping)", i.e. you don't have to use
289+
[`raw`](https://twig.symfony.com/doc/3.x/filters/raw.html) to render the XML.

src/Os2formsFordelingskomponentTwigExtension.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace Drupal\os2forms_fordelingskomponent;
66

77
use Twig\Extension\AbstractExtension;
8+
use Twig\TwigFilter;
89
use Twig\TwigFunction;
910

1011
/**
@@ -46,4 +47,44 @@ static function (string $argument, ?string $langcode = NULL): float {
4647
return $functions;
4748
}
4849

50+
/**
51+
* {@inheritdoc}
52+
*/
53+
#[\Override]
54+
public function getFilters(): array {
55+
$filters[] = new TwigFilter(
56+
'os2forms_fordelingskomponent_xml_encode',
57+
static function (array $value, string $numeric_key_prefix = 'key_'): string {
58+
// https://stackoverflow.com/a/19987539
59+
$toXml = static function (\SimpleXMLElement $object, array $data) use (&$toXml, $numeric_key_prefix) {
60+
foreach ($data as $key => $value) {
61+
// If the key is an integer, it needs text with it to actually work.
62+
$valid_key = is_numeric($key) ? $numeric_key_prefix . $key : $key;
63+
$new_object = $object->addChild(
64+
$valid_key,
65+
is_array($value) ? NULL : htmlspecialchars((string) $value)
66+
);
67+
68+
if (is_array($value)) {
69+
$toXml($new_object, $value);
70+
}
71+
}
72+
};
73+
74+
$sxe = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root/>');
75+
$toXml($sxe, $value);
76+
77+
$fragment = '';
78+
foreach ($sxe->xpath('/root/*') as $child) {
79+
$fragment .= $child->asXML();
80+
}
81+
82+
return $fragment;
83+
},
84+
['is_safe' => ['html']]
85+
);
86+
87+
return $filters;
88+
}
89+
4990
}

0 commit comments

Comments
 (0)