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

99 lines
2.5 KiB
PHP

<?php
namespace KupShop\FeedGeneratorBundle\XSD\Definition;
use KupShop\FeedGeneratorBundle\XSD\Parser;
use KupShop\FeedGeneratorBundle\XSD\ParserUtil;
/**
* Common class to be extended by all XML schema nodes, that are to be serialized.
*/
abstract class SerializableNode implements SerializableInterface
{
protected \DOMXPath $xpathInstance;
protected \DOMElement $element;
protected \ArrayObject $typeContext;
public function __construct(\DOMXPath $xpath, \DOMElement $element, \ArrayObject $typeContext)
{
$this->xpathInstance = $xpath;
$this->element = $element;
$this->typeContext = $typeContext;
}
/**
* Execute XPath query relative to current element.
*
* @return \DOMNodeList|false|mixed
*/
protected function xpath(string $query)
{
return $this->xpathInstance->query($query, $this->element);
}
public function getAppInfo(): array
{
$prefix = Parser::$xsdNamespacePrefix;
$res = $this->xpath("{$prefix}:annotation/{$prefix}:appinfo");
if ($res->length !== 1 || !($res->item(0) instanceof \DOMElement)) {
return [];
}
return (array) ParserUtil::xmlKeyValue($res->item(0), true);
}
public function getDocumentation(): string
{
$prefix = Parser::$xsdNamespacePrefix;
$res = $this->xpath("{$prefix}:annotation/{$prefix}:documentation");
if ($res->length !== 1 || !($res->item(0) instanceof \DOMElement)) {
return '';
}
return trim($res->item(0)->textContent);
}
/**
* Get \DOMElement instances from children of current element.
*
* @return \DOMElement[]
*/
public function getChildElements(): array
{
$ns = Parser::$xsdNamespacePrefix;
$filterFunc = function (\DOMElement $elem) use ($ns) {
return $elem->tagName !== "{$ns}:annotation";
};
return array_filter(ParserUtil::filterElements($this->element->childNodes), $filterFunc);
}
public function getAttributes(): array
{
$attributes = [];
foreach ($this->element->attributes as $attr) {
$attributes[$attr->name] = $attr->value;
}
return $attributes;
}
public function serialize(): array
{
$elem = array_merge(
$this->getAppInfo(),
$this->getAttributes(),
);
$docs = $this->getDocumentation();
if (!empty($docs)) {
$elem['documentation'] = $docs;
}
return $elem;
}
}