<?php

    # http://code.google.com/p/lexa-xml-serialization/
    # MIT License
    # Generated on Sep 12, 2010 16:08

    namespace XmlSerialization;

    class ClassMeta {
        private $shortName;
        private $namespace;
        private $xmlRoot;
		private $xmlNamespace;

        private $reflectors = array();
        private $props = array(); // [propName] -> array(xmlName, isElement)
        private $attrs = array(); // [attrName] -> array(propName, valueType)
        private $els = array();   // [elementName] -> array(propName, valueType)

        /** @param mixed $class An instance or a class name */
        public function __construct($class) {
            $r = new \ReflectionClass($class);
            $this->shortName = $r->getShortName();
            $this->namespace = $r->getNamespaceName();
            $this->xmlRoot = $this->receiveXmlRoot($r->getDocComment());
			$this->xmlNamespace = $this->receiveXmlNameSpace($r->getDocComment());

            $current = $r;
            while($current) {
                foreach($current->getProperties() as $p) {                    
                    if($p->getDeclaringClass()->name != $current->name)
                        continue;
                    $this->processProperty($p);           
                }
                $current = $current->getParentClass();
            }
        }

        private function receiveXmlRoot($docComment) {
            foreach(Annotation::parse($docComment) as $a) {
                if($a->getName() == "root" && $a->getParamCount() > 0)
                    return $a->getParam(0);
            }
        }
		
		private function receiveXmlNameSpace($docComment) {
            foreach(Annotation::parse($docComment) as $a) {
                if($a->getName() == "namespace" && $a->getParamCount() > 0)
                    return $a->getParam(0);
            }
        }

        private function processProperty(\ReflectionProperty $p) {
            $registered = false;
            foreach(Annotation::parse($p->getDocComment()) as $a) {
                if($a->getName() != "element" && $a->getName() != "attribute")
                    continue;

                if($p->isStatic())
                    $this->fail("Static property '{$p->name}' cannot be serialized");

                if(!$registered) {
                    $p->setAccessible(true);
                    $this->reflectors[$p->name] = $p;
                    $registered = true;
                }
                
                $type = "";
                if($a->getParamCount() > 0)
				{
                    $type = explode("^", $a->getParam(0));
					if (count($type) > 1)
						$containerType = $type[1];
						
					$type = $type[0];
				}

                $xmlName = $p->name;
                if($a->getParamCount() > 1)
                    $xmlName = $a->getParam(1);
					
                $isElement = $a->getName() == "element";

                if($this->hasXmlNameForProperty($p->name))
                    $this->fail("Duplicate xml name for property name '{$p->name}'");

                if(!array_key_exists($p->name, $this->props))
                    $this->props[$p->name] = array();
                $this->props[$p->name] = array($xmlName, $isElement);

                if($isElement) {
                    if($this->hasPropertyForElement($xmlName))
                        $this->fail("Duplicate element '$xmlName'");
                    $this->els[$xmlName] = array($p->name, $type);
					if (isSet($containerType))
						array_push($this->els[$xmlName], $containerType);
                } else {
                    if($this->hasPropertyForAttribute($xmlName))
                        $this->fail("Duplicate attribute '$xmlName'");
                    $this->attrs[$xmlName] = array($p->name, $type);
					if (isSet($containerType))
						array_push($this->attrs[$xmlName], $containerType);
                }
            }
        }

        function getClassName() {
            if($this->namespace)
                return $this->namespace . "\\" . $this->shortName;
            return $this->shortName;
        }

        function getNamespace() {
            return $this->namespace;
        }

        function getXmlRoot() {
            if(!$this->xmlRoot)
                return $this->shortName;
            return $this->xmlRoot;
        }
		
		function getXmlNamespace() {
			return $this->xmlNamespace;
		}

        function getPropertyNames() {
            return array_keys($this->props);
        }

        function getAttributeNames() {
            return array_keys($this->attrs);
        }

        function getAttributeNamesForProperty($propName) {
            $result = array();
            foreach($this->attrs as $attrName => $data) {
                if($data[0] == $propName)
                    $result[] = $attrName;
            }
            return $result;
        }

        function getElementNames() {
            return array_keys($this->els);
        }

        function getElementNamesForProperty($propName) {
            $result = array();
            foreach($this->els as $elementName => $data) {
                if($data[0] == $propName)
                    $result[] = $elementName;
            }
            return $result;
        }

        function getPropertyValue($obj, $propName) {
            return $this->reflectors[$propName]->getValue($obj);
        }

        function setPropertyValue($obj, $propName, $value) {
            $this->reflectors[$propName]->setValue($obj, $value);
        }

        function getAttributeName($propName) {
            if(!$this->hasAttributeForProperty($propName))
                return null;
            return $this->props[$propName][0];
        }

        function getElementName($propName) {
            if(!$this->hasElementForProperty($propName))
                return null;
            return $this->props[$propName][0];
        }

        function getPropertyNameForAttribute($attrName) {
            if(!$this->hasPropertyForAttribute($attrName))
                return null;
            return $this->attrs[$attrName][0];
        }

        function getPropertyNameForElement($elementName) {
            if(!$this->hasPropertyForElement($elementName))
                return null;
            return $this->els[$elementName][0];
        }
		
		function isPropertyArray($propName) {
			if($this->hasPropertyForElement($propName)) {
				return count($this->els[$propName]) > 2 && $this->els[$propName][2] === "array";
			} else {
				return false;
			}
		}
		
		function isSimpleList($propName) {
			if($this->hasPropertyForElement($propName)) {
				return count($this->els[$propName]) > 2 && $this->els[$propName][2] === "listOf";
			} else {
				return false;
			}
		}

        function getPropertyTypeForAttribute($attrName) {
            if(!$this->hasPropertyForAttribute($attrName))
                return null;
            return $this->attrs[$attrName][1];
        }

        function getPropertyTypeForElement($elementName) {
            if(!$this->hasPropertyForElement($elementName))
                return null;
            return $this->els[$elementName][1];
        }
				
        function getPropertyContainerTypeForElement($elementName) {
            if(!$this->hasPropertyForElement($elementName) || count($this->els[$elementName]) < 3)
                return null;
            return $this->els[$elementName][2];
        }

        private function hasXmlNameForProperty($propName) {
            return array_key_exists($propName, $this->props);
        }

        private function hasAttributeForProperty($propName) {
            if(!$this->hasXmlNameForProperty($propName))
                return false;
            return !$this->props[$propName][1];
        }

        private function hasElementForProperty($propName) {
            if(!$this->hasXmlNameForProperty($propName))
                return false;
            return $this->props[$propName][1];
        }

        private function hasPropertyForAttribute($attrName) {
            return array_key_exists($attrName, $this->attrs);
        }

        private function hasPropertyForElement($elementName) {
            return array_key_exists($elementName, $this->els);
        }

        private function fail($message) {
            throw new \RuntimeException("Xml metadata error for {$this->getClassName()}: $message");
        }

    }

    class ClassMetaStore {
        private static $instance;

        /** @return ClassMetaStore */
        static function get() {
            if(!self::$instance)
                self::$instance = new ClassMetaStore();
            return self::$instance;
        }

        static function set(ClassMetaStore $store) {
            self::$instance = $store;
        }

        /** @return ClassMeta */
        static function getMeta($class) {
            if(is_object($class))
                $class = get_class($class);
            $store = self::get();
            $meta = $store->getMetaCore($class);
            if(!$meta) {
                $meta = new ClassMeta($class);
                $store->registerMeta($meta);
            }
            return $meta;
        }

        protected $data = array();

        protected function getMetaCore($className) {
            $key = $this->getKey($className);
            if(array_key_exists($key, $this->data))
                return $this->data[$key];
            return null;
        }

        protected function registerMeta(ClassMeta $meta) {
            $key = $this->getKey($meta->getClassName());
            $this->data[$key] = $meta;
        }

        protected function getKey($className) {
            return ltrim(strtolower($className), "\\");
        }

    }

    class XmlSerializer {

        // Serialization
        
        static function serialize($obj) {
            $doc = new \DOMDocument();
            $root = $doc->createElement(ClassMetaStore::getMeta($obj)->getXmlRoot());
            $root->setAttribute("xmlns", ClassMetaStore::getMeta($obj)->getXmlNamespace());
            self::serializeObject($obj, $root);
            $doc->appendChild($root);
            return $doc;
        }

        private static function serializeObject($obj, \DOMElement $target) {
            $meta = ClassMetaStore::getMeta($obj);
            foreach($meta->getPropertyNames() as $propName) {
                $value = $meta->getPropertyValue($obj, $propName);

                if((is_array($value) || $value instanceof \Traversable) && !$meta->isSimpleList($propName)) {
                    foreach($value as $key => $item) {
                        if(!is_int($key))
                            throw new \RuntimeException("Collections with associative indexing cannot be serialized");
                        self::serializeProperty($meta, $propName, $item, $target);
                    }
                } else {
                    self::serializeProperty($meta, $propName, $value, $target);
                }
            }
        }

        private static function serializeProperty(ClassMeta $meta, $propName, $value, \DOMElement $target) {
            if($value === null)
                return;
            
			$valueType = "";

            $attrName = $meta->getAttributeName($propName);
            if($attrName) {
				$valueType = $meta->getPropertyTypeForAttribute($propName);
                $target->setAttribute($attrName, self::formatAtomicValue($propName, $meta->getClassName(), $value, $valueType));
            }

            $elementName = $meta->getElementName($propName);
            if($elementName) {
				$valueType = $meta->getPropertyTypeForElement($propName);
				$container = $meta->getPropertyContainerTypeForElement($propName);
				
                $child = $target->ownerDocument->createElement($elementName);
                if(self::isObject($value) && !$meta->isSimpleList($propName)) {
                     self::serializeObject($value, $child);
                } else {
                    $text = self::formatAtomicValue($propName, $meta->getClassName(), $value, $valueType, $container);
                    $child->appendChild($target->ownerDocument->createTextNode($text));
                }
                $target->appendChild($child);
            }

            if(!$attrName && !$elementName)
				self::ThrowUnableSerializeException($self::getValueType($value), $valueType, $propName, $meta->getClassName());
        }

        private static function getValueType($value) {
            if(is_object($value))
                return get_class($value);
            return gettype($value);
        }
		
		private static function ThrowUnableSerializeException($valueType, $xmlType, $propName, $className) {			
			throw new \InvalidArgumentException("Don't know how to serialize value of type '$valueType' to xml type '$xmlType' for property '$propName' of class '$className'");
		}

        private static function isObject($value) {
            return is_object($value) && !($value instanceof \DateTime);
        }

        private static function formatAtomicValue($propName, $className, $value, $valueXmlType, $containerType = null) {
			if ($valueXmlType == "xs:bool" || $valueXmlType == "xs:boolean") {
				if(is_bool($value))
					return $value ? "true" : "false";
				else
					self::ThrowUnableSerializeException(self::getValueType($value), "xs:bool", $propName, $className);
			}
			
			if ($valueXmlType == "xs:date" || $valueXmlType == "xs:time" || $valueXmlType == "xs:dateTime") {			
				if($value instanceof \DateTime) {
					$date = $value->format("Y-m-d");
					$time = $value->format("H:i:s");
					if ($valueXmlType == "xs:time")
						return $time;
					if ($valueXmlType == "xs:date")
						return $date;
					
					return $date."T".$time;
				}
				
				self::ThrowUnableSerializeException(self::getValueType($value), $valueXmlType, $propName, $className);
			}
			
			if ($valueXmlType == "xs:long") {
				$type = self::getValueType($value);//int or double
				if ($type == "double" || $type == "float") {
					if ($value - round($value) != 0)
						self::ThrowUnableSerializeException($type, "xs:long", $propName, $className);
						
					return number_format($value, 0, '', '');
				}
			}
			
			//check if that is list type
			if ($containerType === "listOf"){
				$ret = "";
				for($i = 0; $i < count($value); $i++){
					$ret .= self::formatAtomicValue($propName, $className, $value[$i], $valueXmlType);
					if ($i != count($value) - 1)
						$ret .= " ";
				}
				
				return $ret;
			}

			//you can extend this method to check casts to "xs:ushort" or to UidType/UrnType/UriType...
            return (string)$value;
        }
       
        // Unserialization

        static function unserialize(\DOMDocument $doc, $className) {            
            $result = new $className;
            self::unserializeObject($result, $doc->documentElement);
            return $result;
        }


        private static function unserializeObject($obj, \DOMElement $source) {
            $meta = ClassMetaStore::getMeta($obj);

            $bag = array();

            foreach($source->attributes as $attribute) {
                $propName = $meta->getPropertyNameForAttribute($attribute->name);
                if(!$propName)
                    continue;
                $valueType = $meta->getPropertyTypeForAttribute($attribute->name);
                $value = self::parseAtomicValue($attribute->value, $valueType);
                self::addPropertyToBag($propName, $value, $bag);
            }

            foreach ($source->childNodes as $child) {
                if(!($child instanceof \DOMElement))
                    continue;
                $propName = $meta->getPropertyNameForElement($child->tagName);
                if(!$propName)
                    continue;
                $valueType = $meta->getPropertyTypeForElement($child->tagName);
                $isObject = !self::isAtomicType($valueType);
                $value = $isObject
                    ? new $valueType
                    : self::parseAtomicValue(trim($child->textContent), $valueType);
                self::addPropertyToBag($propName, $value, $bag);
                if($isObject)
                    self::unserializeObject($value, $child);
            }

            foreach($bag as $propName => $data) {
				if ($meta->isPropertyArray($propName) && !is_array($data)) {
					$data = array($data);
				} else if ($meta->isSimpleList($propName)) {
					$data = explode(" ", $data);
				}
                $currentValue = $meta->getPropertyValue($obj, $propName);
                if(is_array($currentValue)) {
                    if(is_array($data)) {
                        $meta->setPropertyValue($obj, $propName, array_merge($currentValue, $data));
                    } else {
                        array_push($currentValue, $data);
                        $meta->setPropertyValue($obj, $propName, $currentValue);
                    }
                } elseif($currentValue instanceof \ArrayAccess) {
                    if(is_array($data)) {
                        foreach($data as $item)
                            $currentValue[] = $item;
                    } else {
                        $currentValue[] = $data;
                    }
                } else {
                    $meta->setPropertyValue($obj, $propName, $data);
                }
            }
        }

        private static function addPropertyToBag($name, $value, array &$bag) {
            if(!array_key_exists($name, $bag)) {
                $bag[$name] = $value;
            } else {
                if(is_array($bag[$name])) {
                    array_push($bag[$name], $value);
                } else {
                    $bag[$name] = array($bag[$name], $value);
                }
            }
        }

        private static function isAtomicType($type) {
			$containerTypes = explode("^", $type);
            return $type == "xs:string"
				|| $type == "xs:int"
				|| $type == "xs:long"
                || $type == "xs:integer"
                || $type == "xs:boolean"
                || $type == "xs:double"
				|| $type == "xs:date"
                || $type == "xs:dateTime"
				|| $type == "xs:time"
                || $type == "xs:unsignedShort"
				|| (count($containerTypes) == 2 && $containerTypes [1] == "listOf");
        }

        private static function parseAtomicValue($value, $type) {
            if($type == "xs:integer" || $type == "xs:int" || $type == "xs:long" || $type == "xs:unsignedShort")
                return intval($value);

            if($type == "xs:boolean" || $type == "xs:bool")
                return strtolower($value) == "true" || intval($value) > 0;

            if($type == "xs:double")
                return doubleval($value);

            if($type == "xs:dateTime" || $type == "xs:time" || $type == "xs:date")
                return new \DateTime($value);
            
            return (string)$value;
        }
    }


    class Annotation {

        /** @return array */
        static function parse($docComment) {
            preg_match_all("/\\@xml(element|attribute|root|namespace)\\s*(?:\\((.*?)\\))?/is", $docComment, $matches, PREG_SET_ORDER);
            $result = array();
            foreach($matches as $match) {
                $annotation = new Annotation;
                $annotation->name = strtolower($match[1]);
                if(count($match) > 2)
                    $annotation->params = preg_split("/\\s*\\,\\s*/", trim($match[2]), -1, PREG_SPLIT_NO_EMPTY);
                $result[] = $annotation;
            }
            return $result;
        }

        private $name;
        private $params;

        protected function __construct() {
        }

        function getName() {
            return $this->name;
        }

        function getParamCount() {
            return count($this->params);
        }

        function getParam($index) {
            return $this->params[$index];
        }

    }
