¤  tinycrud project site > /schema/table2xsd.php
<?
/*
Copyright (c) 2004-2007, Dave Gullo <dave@gullo.tv>
{{{
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the Dave Gullo nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}}}
*/

require_once $_SERVER['DOCUMENT_ROOT'] ."/lib/classes/Database.php";
require_once 
$_SERVER['DOCUMENT_ROOT'] ."/lib/classes/ErrorHandler.php";

$conn = new Database();
if (empty(
$_REQUEST['c'])) {
  echo 
"Missing c :: class";
  exit;
}
//-= Look to the application.xml file for Class-to-table type binding
$dom = new DomDocument('1.0''utf-8');
$dom->load('application.xml');
$xp = new DomXPath($dom);
if (empty(
$_REQUEST['d'])) {
  
$database $xp->query("/application/@database")->item(0)->textContent;
} else {
  
//-= It is possible to pass in the DB for situations where your model spans databases
  
$database $_REQUEST['d'];
}
$table $xp->query("/application/class[@name='{$_REQUEST['c']}']/@table")->item(0)->textContent;
if (
strlen($table) < 3) {
  throw new 
Exception("Table no found for class {$_REQUEST['c']}");
  exit;
}
$conn->query("USE $database");
$rootelement strtolower($_REQUEST['c']); 
$sql "SHOW COLUMNS FROM $table";
$result $conn->getQuery($sql);
if (
mysqli_errno($conn) == 1146) {
  
$sql "SHOW COLUMNS FROM $table"."s";
  
$result $conn->getQuery($sql);
}

$dom = new DomDocument('1.0''UTF-8'); 
$schema $dom->createElementNS('http://www.w3.org/2001/XMLSchema''xsd:schema');
//-= Add our axis for mysql metadata
$mysql $dom->createAttribute('xmlns:mysql');
$mysql->appendChild($dom->createTextNode("http://drknowledge.com/ns/mysqlxb"));
$schema->appendChild($mysql);
//-= Add our axis for php metadata
$php $dom->createAttribute('xmlns:php');
$php->appendChild($dom->createTextNode("http://drknowledge.com/ns/phpxb"));
$schema->appendChild($php);
$dom->appendChild($schema);

//-= Add a reference to 'Types.xsd' which is the application list of types not native to XSD
$include $dom->createElement("xsd:include");
$location $dom->createAttribute("schemaLocation");
$location->appendChild($dom->createTextNode("Types.xsd"));
$include->appendChild($location);
$schema->appendChild($include);

$root $dom->createElement('xsd:element');
$name $dom->createAttribute('name');
$value $dom->createTextNode($rootelement);
$name->appendChild($value);
$root->appendChild($name);
$schema->appendChild($root);

//-= All of our metadata for php and mysql belong under the xsd:annotation subtree, as defined in the XSD standard
//-= See: http://www.zvon.org/xxl/XMLSchemaTutorial/Output/ser_annotation_st1.html
$an $dom->createElement("xsd:annotation");
$root->appendChild($an);
$ai $dom->createElement("xsd:appinfo");
$an->appendChild($ai);
$db $dom->createElement("mysql:database");
$db->appendChild($dom->createTextNode($database));
$ai->appendChild($db);
$db $dom->createElement("mysql:tableName");
$db->appendChild($dom->createTextNode($table));
$ai->appendChild($db);
$db $dom->createElement("php:className");
$db->appendChild($dom->createTextNode($_REQUEST['c']));
$ai->appendChild($db);

//-= Get a valid unique id to generate our default toXML test case, this will be used by make validate
//-= this requires our primary key be an expansion of the table name, eg: customer table has a customerid, product has a productid...
try {
  
$sql "SELECT max($rootelement"."id) AS id FROM $database.$table";
  
$id $conn->getObject($sql);
  if (
$id->id 0) {
    
$db $dom->createElement("mysql:testKey");
    
$db->appendChild($dom->createTextNode($id->id));
    
$ai->appendChild($db);
  }
} catch (
Exception $e) {
  
//-= Oh well, we tried...
}

$complexType $dom->createElement('xsd:complexType');
$all $dom->createElement('xsd:all');
$complexType->appendChild($all);
$root->appendChild($complexType);

//-= Now loop through all of our columns, and spit out all the visible members of this class
while ($col mysqli_fetch_object($result)) {
  if (
$col->Key == 'PRI') {
    
$db $dom->createElement("mysql:primaryKey");
    
$db->appendChild($dom->createTextNode($col->Field));
    
$ai->appendChild($db);
  }
  if (!
eregi("lastmodified|$rootelement"."id$"$col->Field)) {
    
$element $dom->createElement('xsd:element');
    
$name $dom->createAttribute('name');
    
$value $dom->createTextNode(eregi_replace($rootelement''$col->Field)); //-= Squeeze out redundant naming of table/colum info
    
$name->appendChild($value);
    
$element->appendChild($name);

    
//-= Min Occurs...
    
$min $dom->createAttribute('minOccurs');
    if (
$col->Null == "YES") {
      
$min->appendChild($dom->createTextNode('0'));
    } else {
      
$min->appendChild($dom->createTextNode('1'));
    } 
    
$element->appendChild($min);

    
//-= Max Occurs...
    
$max $dom->createAttribute('maxOccurs');
    
$max->appendChild($dom->createTextNode('1'));
    
$element->appendChild($max);

    
//-= Here is where the magic happens in terms of binding mysql type swith xsd types.  If I haven't handled your column type, please add it here...
    
$type $dom->createAttribute('type');
    if (
eregi('^varchar|^enum|^text|^datetime|^char|^date'$col->Type)) {
      
$type->appendChild($dom->createTextNode('xsd:string')); 
    } elseif (
eregi('^enum'$col->Type)) {
      
$type->appendChild($dom->createTextNode('xsd:string'));
    } elseif (
eregi('^text'$col->Type)) {
      
$type->appendChild($dom->createTextNode('xsd:string')); 
    } elseif (
eregi('^decimal|^float|^double'$col->Type)) {
      
$type->appendChild($dom->createTextNode('positiveFloatOrNULL')); 
    } elseif (
eregi('^timestamp'$col->Type)) {
      
$type->appendChild($dom->createTextNode('xsd:positiveInteger')); 
    } elseif (
eregi('^int|^tinyint|^smallint'$col->Type)) {
      if (
eregi("unsigned"$col->Type)) {
        if (
$col->Null == "YES") {
          
$type->appendChild($dom->createTextNode('positiveIntegerOrNULL')); 
        } else {
          
$type->appendChild($dom->createTextNode('integerOrNULL')); 
        }
      } else {
        
$type->appendChild($dom->createTextNode('integerOrNULL')); 
      }
    } else {
      
$type->appendChild($dom->createTextNode('xsd:string')); 
    }
    
$element->appendChild($type);
  
    
//-= Inject all of the necessary php/mysql metatdata here under xsd:appinfo
    
$an $dom->createElement('xsd:annotation');
    
$ai $dom->createElement('xsd:appinfo');
    
$an->appendChild($ai);
    
$db $dom->createElement('mysql:columnName');
    
$db->appendChild($dom->createCDATASection($col->Field));
    
$ai->appendChild($db);
    
$db $dom->createElement('mysql:datatype'); 
    
$db->appendChild($dom->createCDATASection($col->Type));
    
$ai->appendChild($db);
    
$db $dom->createElement('php:visibility'); 
    
$db->appendChild($dom->createCDATASection('public'));
    
$ai->appendChild($db);
    
//-= Explode all enum members here, so we can type-check them in the class, and create pull-downs in our HTML forms...
    
if (eregi('^enum'$col->Type)) {
      
$enums split(","preg_replace("/enum|\(|\)|'/"''$col->Type));
      foreach(
$enums as $enum) {
        
$en $dom->createElement('mysql:enum'); 
        
$en->appendChild($dom->createCDATASection($enum));
        
$ai->appendChild($en);
      }
    }
    
$element->appendChild($an);
    
$all->appendChild($element);
  } elseif (
eregi("lastmodified"$col->Field)) {
    
//-= lastmodified in the database is a magic field, it should be an positive integer timestamp
    //-= and as such it is not a standard elemen in the serialized view of our resulting classes, 
    //-= but rather an attribute on the root of the resulting xml.
    
$lm $dom->createElement("xsd:attribute");
    
$name $dom->createAttribute("name");
    
$name->appendChild($dom->createTextNode("lastmodified"));
    
$lm->appendChild($name);
    
$type $dom->createAttribute("type");
    
$type->appendChild($dom->createTextNode("xsd:positiveInteger"));
    
$lm->appendChild($type);
    
$use $dom->createAttribute("use");
    
$use->appendChild($dom->createTextNode("required"));
    
$lm->appendChild($use);
    
$an $dom->createElement("xsd:annotation");
    
$root->appendChild($an);
    
$ai $dom->createElement("xsd:appinfo");
    
$an->appendChild($ai);
    
$db $dom->createElement("mysql:columnName");
    
$db->appendChild($dom->createTextNode('lastmodified'));
    
$ai->appendChild($db);
    
$lm->appendChild($an);
    
$complexType->appendChild($lm);
  } elseif (
eregi("^$rootelement"."id$"$col->Field)) {
    
//-= The primary key of this class is also magic, it gets appended to as an attribute as well.
    //-= Since it is immutable, it belongs out of the scope of enumurable elements within our $class->toXML();
    
$lm $dom->createElement("xsd:attribute");
    
$name $dom->createAttribute("name");
    
$name->appendChild($dom->createTextNode("id"));
    
$lm->appendChild($name);
    
$type $dom->createAttribute("type");
    
$type->appendChild($dom->createTextNode("xsd:positiveInteger"));
    
$lm->appendChild($type);
    
$use $dom->createAttribute("use");
    
$use->appendChild($dom->createTextNode("required"));
    
$lm->appendChild($use);
    
$an $dom->createElement("xsd:annotation");
    
$root->appendChild($an);
    
$ai $dom->createElement("xsd:appinfo");
    
$an->appendChild($ai);
    
$db $dom->createElement("mysql:columnName");
    
$db->appendChild($dom->createTextNode($col->Field));
    
$ai->appendChild($db);
    
$lm->appendChild($an);
    
$complexType->appendChild($lm);
  }
}
//-= Let's get our XSD!
header("Content-type: text/xml");
echo  
$dom->saveXML();
?>