3 namespace Consolidation\OutputFormatters\StructuredData\Xml;
5 class XmlSchema implements XmlSchemaInterface
7 protected $elementList;
9 public function __construct($elementList = [])
13 '*' => ['description'],
15 $this->elementList = array_merge_recursive($elementList, $defaultElementList);
18 public function arrayToXML($structuredData)
20 $dom = new \DOMDocument('1.0', 'UTF-8');
21 $topLevelElement = $this->getTopLevelElementName($structuredData);
22 $this->addXmlData($dom, $dom, $topLevelElement, $structuredData);
26 protected function addXmlData(\DOMDocument $dom, $xmlParent, $elementName, $structuredData)
28 $element = $dom->createElement($elementName);
29 $xmlParent->appendChild($element);
30 if (is_string($structuredData)) {
31 $element->appendChild($dom->createTextNode($structuredData));
34 $this->addXmlChildren($dom, $element, $elementName, $structuredData);
37 protected function addXmlChildren(\DOMDocument $dom, $xmlParent, $elementName, $structuredData)
39 foreach ($structuredData as $key => $value) {
40 $this->addXmlDataOrAttribute($dom, $xmlParent, $elementName, $key, $value);
44 protected function addXmlDataOrAttribute(\DOMDocument $dom, $xmlParent, $elementName, $key, $value)
46 $childElementName = $this->getDefaultElementName($elementName);
47 $elementName = $this->determineElementName($key, $childElementName, $value);
48 if (($elementName != $childElementName) && $this->isAttribute($elementName, $key, $value)) {
49 $xmlParent->setAttribute($key, $value);
52 $this->addXmlData($dom, $xmlParent, $elementName, $value);
55 protected function determineElementName($key, $childElementName, $value)
57 if (is_numeric($key)) {
58 return $childElementName;
60 if (is_object($value)) {
61 $value = (array)$value;
63 if (!is_array($value)) {
66 if (array_key_exists('id', $value) && ($value['id'] == $key)) {
67 return $childElementName;
69 if (array_key_exists('name', $value) && ($value['name'] == $key)) {
70 return $childElementName;
75 protected function getTopLevelElementName($structuredData)
80 protected function getDefaultElementName($parentElementName)
82 $singularName = $this->singularForm($parentElementName);
83 if (isset($singularName)) {
89 protected function isAttribute($parentElementName, $elementName, $value)
91 if (!is_string($value)) {
94 return !$this->inElementList($parentElementName, $elementName) && !$this->inElementList('*', $elementName);
97 protected function inElementList($parentElementName, $elementName)
99 if (!array_key_exists($parentElementName, $this->elementList)) {
102 return in_array($elementName, $this->elementList[$parentElementName]);
105 protected function singularForm($name)
107 if (substr($name, strlen($name) - 1) == "s") {
108 return substr($name, 0, strlen($name) - 1);
112 protected function isAssoc($data)
114 return array_keys($data) == range(0, count($data));