PHP Classes

File: SerializeTypedStruct.class.php

Recommend this page to a friend!
  Packages of Tom Schaefer   TypeSafeStruct   SerializeTypedStruct.class.php   Download  
File: SerializeTypedStruct.class.php
Role: Class source
Content type: text/plain
Description: Sample Base class extension => serializes an object's properties
Class: TypeSafeStruct
Manipulate type safe objects
Author: By
Last change: chg
Date: 17 years ago
Size: 1,637 bytes
 

Contents

Class file image Download
<?php
/**
 * @author Thomas Schaefer
 * @mail scaphare@gmail.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, ",")
            );
    }
    
}