Files
2025-08-02 16:30:27 +02:00

111 lines
3.3 KiB
PHP

<?php
namespace KupShop\FeedGeneratorBundle\XSD;
final class ParserUtil
{
/**
* Converts an associative array into a flat key => value list. <br />
* ['a' => ['b' => ['c' => 'd']], 'e' => 'f'] becomes ['a.b.c' => 'd', 'e' => 'f'].
*/
public static function arrayFlatten(array $deepAssocArray, string $separator = '.'): array
{
$iter = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($deepAssocArray));
$result = [];
foreach ($iter as $leafValue) {
$keys = [];
foreach (range(0, $iter->getDepth()) as $depth) {
$keys[] = $iter->getSubIterator($depth)->key();
}
$result[implode($separator, $keys)] = $leafValue;
}
return $result;
}
public static function xmlKeyValue(\DOMElement $element, bool $flat = false)
{
$serializedElement = [];
if ($element->hasAttributes()) {
$serializedElement['attributes'] = [];
}
foreach ($element->attributes as $attr) {
$serializedElement['attributes'][$attr->name] = $attr->value;
}
$children = self::filterElements($element->childNodes);
if (count($children) > 0) {
if (!$flat) {
$serializedElement['children'] = [];
}
} elseif (!isset($serializedElement['attributes'])) {
return trim($element->textContent);
} else {
$serializedElement['value'] = trim($element->textContent);
}
foreach ($children as $child) {
$parsedChild = self::xmlKeyValue($child);
$name = $parsedChild['attributes']['name'] ?? $child->tagName;
if ($flat) {
$serializedElement[$name] = $parsedChild;
} else {
$serializedElement['children'][$name] = $parsedChild;
}
}
return $serializedElement;
}
/**
* @return \DOMElement[]
*/
public static function filterElements(\DOMNodeList $list): array
{
$elemList = [];
foreach ($list as $node) {
if ($node instanceof \DOMElement) {
$elemList[] = $node;
}
}
return $elemList;
}
/**
* Converts associative array from the output of SerializableInterface::serialize
* into parent => [child0.name, child1.name, ...] list.
*
* @param array $array output of the serialize function
* @param array $nodeKeysKeep keep certain keys from non-leaf nodes
* (will be in the same array as child names of the parent node)
*/
public static function keyValueChildren(array $array, array $nodeKeysKeep = []): array
{
$elem = [];
if (empty($array['name'])) {
foreach ($array as $child) {
$elem += self::keyValueChildren($child, $nodeKeysKeep);
}
} elseif (!empty($array['children'])) {
$elem[$array['name']] = self::keyValueChildren($array['children'], $nodeKeysKeep);
foreach ($nodeKeysKeep as $key) {
if (!empty($array[$key])) {
$elem[$array['name']][$key] = $array[$key];
}
}
} else {
$elem[$array['name']] = $array;
}
return $elem;
}
}