diff --git a/src/UNL/Alert/ArrayObject.php b/src/UNL/Alert/ArrayObject.php new file mode 100644 index 0000000000000000000000000000000000000000..b8c079e7fc6dd8df6a300658a66f4c67d3c4385d --- /dev/null +++ b/src/UNL/Alert/ArrayObject.php @@ -0,0 +1,85 @@ +<?php + +class UNL_Alert_ArrayObject extends ArrayObject +{ + /** + * Returns an XML string representation of this object's internal data + * + * @param string $rootName The element name for the root wrapper element + * @param string $rootNS The default namespace for the root element + * @param string $numericName The element name to use for top level numeric array indicies + * @return string + */ + public function toXML($rootName = 'root', $rootNS = '', $numericName = 'item') + { + $document = new DOMDocument('1.0', 'UTF-8'); + + if ($rootNS) { + $root = $document->createElementNS($rootNS, $rootName); + } else { + $root = $document->createElement($rootName); + } + $document->appendChild($root); + + $data = $this->getArrayCopy(); + $this->appendToXml($document, $root, $data, $numericName); + + return $document->saveXML(); + } + + /** + * Iterates over $data array and appends elements created with $document + * to the $node. If the array is numerically indexed, the $rootName will + * be used as the element name. + * + * @param DOMDocument $document + * @param DOMNode $node + * @param array $data + * @param string $rootName + */ + protected function appendToXml($document, $node, $data, $rootName) + { + $isAssoc = !count(array_filter(array_keys($data), 'is_numeric')); + + foreach ($data as $key => $value) { + $childName = $key; + if (is_numeric($key)) { + $childName = $rootName; + + if ($isAssoc) { + continue; + } + } + + if (is_array($value)) { + if ($isAssoc) { + $child = $node; + } else { + $child = $document->createElement($childName); + $node->appendChild($child); + } + $this->appendToXml($document, $child, $value, $childName); + } else { + $child = $document->createElement($childName, $value); + $node->appendChild($child); + } + } + } + + /** + * Returns a JSON encoded string representation of this object's internal data + * + * @param string $rootWrapper + * @return string + */ + public function toJSON($rootWrapper = null) + { + $data = $this->getArrayCopy(); + if (empty($data)) { + $data = new stdClass(); + } elseif (!empty($rootWrapper)) { + $data = array($rootWrapper => $data); + } + return json_encode($data); + } +} \ No newline at end of file