mvc: retain attributes in single values; closes #4633

Second try: retain attribute values as sibling nodes with
a name up front.  If the sibling does not exist fail silently
like before.  At least from testing this no longer produces
any shift in the config.xml between string nodes with attributes.

Test XML:

<?xml version="1.0"?>
<opnsense>
  <staticroutes version="1.0.0"/>
  <someotherthing version="1.0.0">
    <foo/>
  </someotherthing>
  <thing version="1.0.0"></thing>
  <alias version="1.0.0"/>
  <doesthisdoit></doesthisdoit>
</opnsense>

Test PHP:

<?php

require_once 'config.inc';

OPNsense\Core\Config::getInstance()->fromArray(load_config_from_file('foo.xml'));
print_r(OPNsense\Core\Config::getInstance()->__toString());

Result XML:

<?xml version="1.0"?>
<opnsense>
  <staticroutes version="1.0.0"/>
  <someotherthing version="1.0.0">
    <foo/>
  </someotherthing>
  <thing version="1.0.0"/>
  <alias version="1.0.0"/>
  <doesthisdoit/>
</opnsense>
This commit is contained in:
Franco Fichtner 2021-09-16 13:43:14 +02:00
parent ca6f461378
commit e7e955f573

View File

@ -1,7 +1,7 @@
<?php
/*
* Copyright (C) 2015 Deciso B.V.
* Copyright (C) 2015-2021 Deciso B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@ -102,7 +102,7 @@ class Config extends Singleton
// copy attributes to @attribute key item
foreach ($node->attributes() as $AttrKey => $AttrValue) {
if (!isset($result['@attributes'])) {
$result['@attributes'] = array();
$result['@attributes'] = [];
}
$result['@attributes'][$AttrKey] = $AttrValue->__toString();
}
@ -147,6 +147,13 @@ class Config extends Singleton
} else {
$result[$xmlNodeName] = $xmlNode->__toString();
}
// copy attributes to xzy@attribute key item
foreach ($xmlNode->attributes() as $AttrKey => $AttrValue) {
if (!isset($result["${xmlNodeName}@attributes"])) {
$result["${xmlNodeName}@attributes"] = [];
}
$result["${xmlNodeName}@attributes"][$AttrKey] = $AttrValue->__toString();
}
}
}
}
@ -206,6 +213,15 @@ class Config extends Singleton
$node->addAttribute($attrKey, $attrValue);
}
continue;
} elseif (strstr($itemKey , '@attributes') !== false) {
$origname = str_replace('@attributes', '', $itemKey);
if (count($node->$origname)) {
// copy xml attributes
foreach ($itemValue as $attrKey => $attrValue) {
$node->$origname->addAttribute($attrKey, $attrValue);
}
}
continue;
} elseif (is_numeric($itemKey)) {
// recurring tag (content), use parent tagname.
$childNode = $node->addChild($parentTagName);