Location: PHPKode > scripts > TypeSafeStruct > typesafestruct/SerializeTypedStruct.class.php
<?php
/**
 * @author Thomas Schaefer
 * @mail hide@address.com
*/
class SerializeTypedStruct {
	
	static function toXML(TypedStruct $o, SimpleXMLElement $parent = NULL) {
		
		if (is_null($parent)) {
			$parent = new SimpleXMLElement(sprintf("<?xml version=\"1.0\"?><%s/>", get_class($o)));
		}
		
		foreach ($o->getProperties() as $name => $type) {
			
			$v = $o->{"get".$name}();
			if (is_null($v)) continue;
			switch ($type) {
				case "bool":
					$parent->addChild($name, (string) ($v)?"true":"false");
					break;
				case "integer":
					$parent->addChild($name, (int)$v);
					break;
				case "timestamp":
					$parent->addChild($name, gmstrftime("%Y-%m-%dT%H:%M:%SZ", $v));
					break;
				case "string":
					$parent->addChild($name, $v);
					break;
			}
		}
		
		return $parent->asXML();
	}
	
	static function sqlInsert(TypedStruct $o, $table) {
		$fields = array();
		$values = array();
		
		foreach ($o->getProperties() as $name => $type) {
			
			$v = $o->{"get".$name}();
			if (is_null($v)) continue;
			
			$fields[] = $name;
			
			switch ($type) {
				case "integer":
					$values[] = is_null($v) ? "NULL" : (int)$v;
					break;
				case "bool":
					$values[] = is_null($v) ? "NULL" : (bool)$v;
					break;
				case "timestamp":
					$values[] = is_null($v) ? "NULL" : gmstrftime('"%Y-%m-%d %H:%M:%S"', $v);
					break;
				case "string":
					$values[] = is_null($v) ? "NULL" : addslashes($v);
					break;
			}
		}
		
		return sprintf('INSERT INTO %s (%s) VALUES (%s)',
			$table,
			join($fields, ","),
			join($values, ",")
			);
	}
	
}
Return current item: TypeSafeStruct