Update to DB_DataObject 1.11.2

Now there's definitely no PHP4 support whatsoever, if there even
was little of it before this commit.
This commit is contained in:
Mikael Nordfeldth 2013-08-12 12:32:39 +02:00
parent f79aec36fe
commit 7d8e199a3f
6 changed files with 1478 additions and 552 deletions

1232
extlib/DB/DataObject.php Normal file → Executable file

File diff suppressed because it is too large Load Diff

28
extlib/DB/DataObject/Cast.php Normal file → Executable file
View File

@ -17,7 +17,7 @@
* @author Alan Knowles <alan@akbkhome.com>
* @copyright 1997-2008 The PHP Group
* @license http://www.php.net/license/3_01.txt PHP License 3.01
* @version CVS: $Id: Cast.php 287158 2009-08-12 13:58:31Z alan_k $
* @version CVS: $Id: Cast.php 326604 2012-07-12 03:02:00Z alan_k $
* @link http://pear.php.net/package/DB_DataObject
*/
@ -395,6 +395,15 @@ class DB_DataObject_Cast {
// this is funny - the parameter order is reversed ;)
return "'".sqlite_escape_string($this->value)."'";
case 'mssql':
if(is_numeric($this->value)) {
return $this->value;
}
$unpacked = unpack('H*hex', $this->value);
return '0x' . $unpacked['hex'];
default:
return PEAR::raiseError("DB_DataObject_Cast cant handle blobs for Database:{$db->dsn['phptype']} Yet");
@ -422,10 +431,10 @@ class DB_DataObject_Cast {
// perhaps we should support TEXT fields???
//
if (!($to & DB_DATAOBJECT_BLOB)) {
return PEAR::raiseError('Invalid Cast from a DB_DataObject_Cast::string to something other than a blob!'.
' (why not just use native features)');
}
// $to == a string field which is the default type (0)
// so we do not test it here. - we assume that number fields
// will accept a string?? - which is stretching it a bit ...
// should probaly add that test as some point.
switch ($db->dsn['phptype']) {
case 'pgsql':
@ -438,6 +447,14 @@ class DB_DataObject_Cast {
case 'mysqli':
return "'".mysqli_real_escape_string($db->connection, $this->value)."'";
case 'mssql':
// copied from the old DB mssql code...?? not sure how safe this is.
return "'" . str_replace(
array("'", "\\\r\n", "\\\n"),
array("''", "\\\\\r\n\r\n", "\\\\\n\n"),
$this->value
) . "'";
default:
return PEAR::raiseError("DB_DataObject_Cast cant handle blobs for Database:{$db->dsn['phptype']} Yet");
@ -544,6 +561,5 @@ class DB_DataObject_Cast {
}

0
extlib/DB/DataObject/Error.php Normal file → Executable file
View File

239
extlib/DB/DataObject/Generator.php Normal file → Executable file
View File

@ -15,7 +15,7 @@
* @author Alan Knowles <alan@akbkhome.com>
* @copyright 1997-2006 The PHP Group
* @license http://www.php.net/license/3_01.txt PHP License 3.01
* @version CVS: $Id: Generator.php 298560 2010-04-25 23:01:51Z alan_k $
* @version CVS: $Id: Generator.php 327926 2012-10-08 02:42:09Z alan_k $
* @link http://pear.php.net/package/DB_DataObject
*/
@ -86,6 +86,13 @@ class DB_DataObject_Generator extends DB_DataObject
*/
var $table; // active tablename
/**
* links (generated)
*
* @var array
* @access private
*/
var $_fkeys; // active tablename
/**
* The 'starter' = call this to start the process
@ -142,6 +149,7 @@ class DB_DataObject_Generator extends DB_DataObject
$t->_database = basename($t->_database);
}
$t->_createTableList();
$t->_createForiegnKeys();
foreach(get_class_methods($class) as $method) {
if (substr($method,0,8 ) != 'generate') {
@ -173,14 +181,17 @@ class DB_DataObject_Generator extends DB_DataObject
function _createTableList()
{
$this->_connect();
$options = &PEAR::getStaticProperty('DB_DataObject','options');
$__DB= &$GLOBALS['_DB_DATAOBJECT']['CONNECTIONS'][$this->_database_dsn_md5];
$db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
$is_MDB2 = ($db_driver != 'DB') ? true : false;
if (is_a($__DB , 'PEAR_Error')) {
if (is_object($__DB) && is_a($__DB , 'PEAR_Error')) {
return PEAR::raiseError($__DB->toString(), null, PEAR_ERROR_DIE);
}
@ -202,7 +213,7 @@ class DB_DataObject_Generator extends DB_DataObject
$__DB->loadModule('Reverse');
}
if ((empty($this->tables) || is_a($this->tables , 'PEAR_Error'))) {
if ((empty($this->tables) || (is_object($this->tables) && is_a($this->tables , 'PEAR_Error')))) {
//if that fails fall back to clasic tables list.
if (!$is_MDB2) {
// try getting a list of schema tables first. (postgres)
@ -218,18 +229,19 @@ class DB_DataObject_Generator extends DB_DataObject
}
}
if (is_a($this->tables , 'PEAR_Error')) {
if (is_object($this->tables) && is_a($this->tables , 'PEAR_Error')) {
return PEAR::raiseError($this->tables->toString(), null, PEAR_ERROR_DIE);
}
// build views as well if asked to.
if (!empty($options['build_views'])) {
if (!$is_MDB2) {
$views = $__DB->getListOf('views');
$views = $__DB->getListOf(is_string($options['build_views']) ?
$options['build_views'] : 'views');
} else {
$views = $__DB->manager->listViews();
}
if (is_a($views,'PEAR_Error')) {
if (is_object($views) && is_a($views,'PEAR_Error')) {
return PEAR::raiseError(
'Error getting Views (check the PEAR bug database for the fix to DB), ' .
$views->toString(),
@ -246,20 +258,33 @@ class DB_DataObject_Generator extends DB_DataObject
foreach($this->tables as $table) {
if (isset($options['generator_include_regex']) &&
!preg_match($options['generator_include_regex'],$table)) {
continue;
} else if (isset($options['generator_exclude_regex']) &&
preg_match($options['generator_exclude_regex'],$table)) {
!preg_match($options['generator_include_regex'],$table)) {
$this->debug("SKIPPING (generator_include_regex) : $table");
continue;
}
if (isset($options['generator_exclude_regex']) &&
preg_match($options['generator_exclude_regex'],$table)) {
continue;
}
$strip = empty($options['generator_strip_schema']) ? false : $options['generator_strip_schema'];
$strip = is_numeric($strip) ? (bool) $strip : $strip;
$strip = (is_string($strip) && strtolower($strip) == 'true') ? true : $strip;
// postgres strip the schema bit from the
if (!empty($options['generator_strip_schema'])) {
$bits = explode('.', $table,2);
$table = $bits[0];
if (count($bits) > 1) {
$table = $bits[1];
if (!empty($strip) ) {
if (!is_string($strip) || preg_match($strip, $table)) {
$bits = explode('.', $table,2);
$table = $bits[0];
if (count($bits) > 1) {
$table = $bits[1];
}
}
}
$this->debug("EXTRACTING : $table");
$quotedTable = !empty($options['quote_identifiers_tableinfo']) ?
$__DB->quoteIdentifier($table) : $table;
@ -272,8 +297,9 @@ class DB_DataObject_Generator extends DB_DataObject
}
if (is_a($defs,'PEAR_Error')) {
if (is_object($defs) && is_a($defs,'PEAR_Error')) {
// running in debug mode should pick this up as a big warning..
$this->debug("Error reading tableInfo: $table");
$this->raiseError('Error reading tableInfo, '. $defs->toString());
continue;
}
@ -300,6 +326,7 @@ class DB_DataObject_Generator extends DB_DataObject
// the temporary table array is now the right one (tables names matching
// with regex expressions have been removed)
$this->tables = $tmp_table;
//print_r($this->_definitions);
}
@ -352,6 +379,12 @@ class DB_DataObject_Generator extends DB_DataObject
$tmpname = tempnam(session_save_path(),'DataObject_');
//print_r($this->_newConfig);
$fh = fopen($tmpname,'w');
if (!$fh) {
return PEAR::raiseError(
"Failed to create temporary file: $tmpname\n".
"make sure session.save_path is set and is writable\n"
,null, PEAR_ERROR_DIE);
}
fwrite($fh,$this->_newConfig);
fclose($fh);
$perms = file_exists($file) ? fileperms($file) : 0755;
@ -368,15 +401,15 @@ class DB_DataObject_Generator extends DB_DataObject
// return PEAR::raiseError($ret->message,null,PEAR_ERROR_DIE);
// }
}
/**
* generate Foreign Keys (for links.ini)
* Currenly only works with mysql / mysqli
/**
* create the data for Foreign Keys (for links.ini)
* Currenly only works with mysql / mysqli / posgtreas
* to use, you must set option: generate_links=true
*
* @author Pascal Schöni
*/
function generateForeignKeys()
function _createForiegnKeys()
{
$options = PEAR::getStaticProperty('DB_DataObject','options');
if (empty($options['generate_links'])) {
@ -387,7 +420,7 @@ class DB_DataObject_Generator extends DB_DataObject
echo "WARNING: cant handle non-mysql and pgsql introspection for defaults.";
return; // cant handle non-mysql introspection for defaults.
}
$this->debug("generateForeignKeys: Start");
$DB = $this->getDatabaseConnection();
$fk = array();
@ -458,6 +491,38 @@ class DB_DataObject_Generator extends DB_DataObject
}
}
$this->_fkeys = $fk;
}
/**
* generate Foreign Keys (for links.ini)
* Currenly only works with mysql / mysqli
* to use, you must set option: generate_links=true
*
* @author Pascal Schöni
*/
function generateForeignKeys()
{
$options = PEAR::getStaticProperty('DB_DataObject','options');
if (empty($options['generate_links'])) {
return false;
}
$__DB = &$GLOBALS['_DB_DATAOBJECT']['CONNECTIONS'][$this->_database_dsn_md5];
if (!in_array($__DB->phptype, array('mysql', 'mysqli', 'pgsql'))) {
echo "WARNING: cant handle non-mysql and pgsql introspection for defaults.";
return; // cant handle non-mysql introspection for defaults.
}
$this->debug("generateForeignKeys: Start");
$fk = $this->_fkeys;
$links_ini = "";
foreach($fk as $table => $details) {
@ -472,16 +537,18 @@ class DB_DataObject_Generator extends DB_DataObject
// it's created on the fly!
$options = PEAR::getStaticProperty('DB_DataObject','options');
if (empty($options['schema_location'])) {
if (!empty($options['schema_location'])) {
$file = "{$options['schema_location']}/{$this->_database}.links.ini";
} elseif (isset($options["ini_{$this->_database}"])) {
$file = preg_replace('/\.ini/','.links.ini',$options["ini_{$this->_database}"]);
} else {
$this->debug("generateForeignKeys: SKIP - schema_location or ini_{database} was not set");
return;
}
$file = "{$options['schema_location']}/{$this->_database}.links.ini";
if (!file_exists(dirname($file))) {
require_once 'System.php';
System::mkdir(array('-p','-m',0755,dirname($file)));
mkdir(dirname($file),0755, true);
}
$this->debug("Writing ini as {$file}\n");
@ -490,6 +557,12 @@ class DB_DataObject_Generator extends DB_DataObject
$tmpname = tempnam(session_save_path(),'DataObject_');
$fh = fopen($tmpname,'w');
if (!$fh) {
return PEAR::raiseError(
"Failed to create temporary file: $tmpname\n".
"make sure session.save_path is set and is writable\n"
,null, PEAR_ERROR_DIE);
}
fwrite($fh,$links_ini);
fclose($fh);
$perms = file_exists($file) ? fileperms($file) : 0755;
@ -615,6 +688,7 @@ class DB_DataObject_Generator extends DB_DataObject
case 'TEXT':
case 'MEDIUMTEXT':
case 'LONGTEXT':
case '_TEXT': //postgres (?? view ??)
$type = DB_DATAOBJECT_STR + DB_DATAOBJECT_TXT;
break;
@ -706,14 +780,20 @@ class DB_DataObject_Generator extends DB_DataObject
//echo "\n{$t->name} => {$t->flags}\n";
$secondary_key_match = isset($options['generator_secondary_key_match']) ? $options['generator_secondary_key_match'] : 'primary|unique';
if (preg_match('/(auto_increment|nextval\()/i',rawurldecode($t->flags))
$m = array();
if (preg_match('/(auto_increment|nextval\(([^)]*))/i',rawurldecode($t->flags),$m)
|| (isset($t->autoincrement) && ($t->autoincrement === true))) {
$sn = 'N';
if ($DB->phptype == 'pgsql' && !empty($m[2])) {
$sn = preg_replace('/[("]+/','', $m[2]);
//echo urldecode($t->flags) . "\n" ;
}
// native sequences = 2
if ($write_ini) {
$keys_out_primary .= "{$t->name} = N\n";
$keys_out_primary .= "{$t->name} = $sn\n";
}
$ret_keys_primary[$t->name] = 'N';
$ret_keys_primary[$t->name] = $sn;
} else if ($secondary_key_match && preg_match('/('.$secondary_key_match.')/i',$t->flags)) {
// keys.. = 1
@ -814,8 +894,8 @@ class DB_DataObject_Generator extends DB_DataObject
//echo "Generating Class files: \n";
$options = &PEAR::getStaticProperty('DB_DataObject','options');
$this->_extends = empty($options['extends']) ? $this->_extends : $options['extends'];
$this->_extendsFile = empty($options['extends_location']) ? $this->_extendsFile : $options['extends_location'];
$this->_extends = empty($options['extends']) ? $this->_extends : $options['extends'];
$this->_extendsFile = empty($options['extends_location']) ? $this->_extendsFile : $options['extends_location'];
foreach($this->tables as $this->table) {
@ -835,6 +915,12 @@ class DB_DataObject_Generator extends DB_DataObject
$tmpname = tempnam(session_save_path(),'DataObject_');
$fh = fopen($tmpname, "w");
if (!$fh) {
return PEAR::raiseError(
"Failed to create temporary file: $tmpname\n".
"make sure session.save_path is set and is writable\n"
,null, PEAR_ERROR_DIE);
}
fputs($fh,$out);
fclose($fh);
$perms = file_exists($outfilename) ? fileperms($outfilename) : 0755;
@ -912,7 +998,6 @@ class DB_DataObject_Generator extends DB_DataObject
$body .= " {$var} \$__table = '{$this->table}'; {$p}// table name\n";
// if we are using the option database_{databasename} = dsn
// then we should add var $_database = here
// as database names may not always match..
@ -924,7 +1009,7 @@ class DB_DataObject_Generator extends DB_DataObject
// Only include the $_database property if the omit_database_var is unset or false
if (isset($options["database_{$this->_database}"]) && empty($GLOBALS['_DB_DATAOBJECT']['CONFIG']['generator_omit_database_var'])) {
$p = str_repeat(' ', max(2, (16 - strlen($this->table))));
$p = str_repeat(' ', max(2, (16 - strlen($this->_database))));
$body .= " {$var} \$_database = '{$this->_database}'; {$p}// database name (used with database_{*} config)\n";
}
@ -972,22 +1057,27 @@ class DB_DataObject_Generator extends DB_DataObject
// grep -r __clone * to find all it's uses
// and replace them with $x = clone($y);
// due to the change in the PHP5 clone design.
$static = 'static';
if ( substr(phpversion(),0,1) < 5) {
$body .= "\n";
$body .= " /* ZE2 compatibility trick*/\n";
$body .= " function __clone() { return \$this;}\n";
}
// simple creation tools ! (static stuff!)
$body .= "\n";
$body .= " /* Static get */\n";
$body .= " function staticGet(\$k,\$v=NULL) { return DB_DataObject::staticGet('{$this->classname}',\$k,\$v); }\n";
// depricated - in here for BC...
if (!empty($options['static_get'])) {
// simple creation tools ! (static stuff!)
$body .= "\n";
$body .= " /* Static get */\n";
$body .= " $static function staticGet(\$k,\$v=NULL) { " .
"return DB_DataObject::staticGet('{$this->classname}',\$k,\$v = null); }\n";
}
// generate getter and setter methods
$body .= $this->_generateGetters($input);
$body .= $this->_generateSetters($input);
$body .= $this->_generateLinkMethods($input);
/*
theoretically there is scope here to introduce 'list' methods
based up 'xxxx_up' column!!! for heiracitcal trees..
@ -1193,7 +1283,7 @@ class DB_DataObject_Generator extends DB_DataObject
$class_prefix = empty($options['class_prefix']) ? '' : $options['class_prefix'];
$this->_extends = empty($options['extends']) ? $this->_extends : $options['extends'];
$this->_extendsFile = empty($options['extends_location']) ? $this->_extendsFile : $options['extends_location'];
$this->_extendsFile = empty($options['extends_location']) ? $this->_extendsFile : $options['extends_location'];
$classname = $this->classname = $this->getClassNameFromTableName($this->table);
@ -1346,7 +1436,74 @@ class DB_DataObject_Generator extends DB_DataObject
return $getters;
}
/**
* Generate link setter/getter methods for class definition
*
* @param string Existing class contents
* @return string
* @access public
*/
function _generateLinkMethods($input)
{
$options = &PEAR::getStaticProperty('DB_DataObject','options');
$setters = '';
// only generate if option is set to true
// generate_link_methods true::
if (empty($options['generate_link_methods'])) {
//echo "skip lm? - not set";
return '';
}
if (empty($this->_fkeys)) {
// echo "skip lm? - fkyes empty";
return '';
}
if (empty($this->_fkeys[$this->table])) {
//echo "skip lm? - no fkeys for {$this->table}";
return '';
}
// remove auto-generated code from input to be able to check if the method exists outside of the auto-code
$input = preg_replace('/(\n|\r\n)\s*###START_AUTOCODE(\n|\r\n).*(\n|\r\n)\s*###END_AUTOCODE(\n|\r\n)/s', '', $input);
$setters .= "\n";
$defs = $this->_fkeys[$this->table];
// $fk[$this->table][$tref[1]] = $tref[2] . ":" . $tref[3];
// loop through properties and create setter methods
foreach ($defs as $k => $info) {
// build mehtod name
$methodName = is_callable($options['generate_link_methods']) ?
$options['generate_link_methods']($k) : $k;
if (!strlen(trim($k)) || preg_match("/function[\s]+[&]?$methodName\(/i", $input)) {
continue;
}
$setters .= " /**\n";
$setters .= " * Getter / Setter for \${$k}\n";
$setters .= " *\n";
$setters .= " * @param mixed (optional) value to assign\n";
$setters .= " * @access public\n";
$setters .= " */\n";
$setters .= (substr(phpversion(),0,1) > 4) ? ' public '
: ' ';
$setters .= "function $methodName() {\n";
$setters .= " return \$this->link('$k', func_get_args());\n";
$setters .= " }\n\n";
}
return $setters;
}
/**
* Generate setter methods for class definition

View File

@ -0,0 +1,485 @@
<?php
/**
* Link tool for DB_DataObject
*
* PHP versions 5
*
* LICENSE: This source file is subject to version 3.01 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_01.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
*
* @category Database
* @package DB_DataObject
* @author Alan Knowles <alan@akbkhome.com>
* @copyright 1997-2006 The PHP Group
* @license http://www.php.net/license/3_01.txt PHP License 3.01
* @version : FIXME
* @link http://pear.php.net/package/DB_DataObject
*/
/**
*
* Example of how this could be used..
*
* The lind method are now in here.
*
* Currenly only supports existing methods, and new 'link()' method
*
*/
/**
* Links class
*
* @package DB_DataObject
*/
class DB_DataObject_Links
{
/**
* @property {DB_DataObject} do DataObject to apply this to.
*/
var $do = false;
/**
* @property {Array|String} load What to load, 'all' or an array of properties. (default all)
*/
var $load = 'all';
/**
* @property {String|Boolean} scanf use part of column name as resulting
* property name. (default false)
*/
var $scanf = false;
/**
* @property {String|Boolean} printf use column name as sprintf for resulting property name..
* (default %s_link if apply is true, otherwise it is %s)
*/
var $printf = false;
/**
* @property {Boolean} cached cache the result, so future queries will use cache rather
* than running the expensive sql query.
*/
var $cached = false;
/**
* @property {Boolean} apply apply the result to this object, (default true)
*/
var $apply = true;
//------------------------- RETURN ------------------------------------
/**
* @property {Array} links key value associative array of links.
*/
var $links;
/**
* Constructor
* -- good ole style..
* @param {DB_DataObject} do DataObject to apply to.
* @param {Array} cfg Configuration (basically properties of this object)
*/
function DB_DataObject_Links($do,$cfg= array())
{
// check if do is set!!!?
$this->do = $do;
foreach($cfg as $k=>$v) {
$this->$k = $v;
}
}
/**
* return name from related object
*
* The relies on a <dbname>.links.ini file, unless you specify the arguments.
*
* you can also use $this->getLink('thisColumnName','otherTable','otherTableColumnName')
*
*
* @param string $field|array either row or row.xxxxx or links spec.
* @param string|DB_DataObject $table (optional) name of table to look up value in
* @param string $link (optional) name of column in other table to match
* @author Tim White <tim@cyface.com>
* @access public
* @return mixed object on success false on failure or '0' when not linked
*/
function getLink($field, $table= false, $link='')
{
static $cache = array();
// GUESS THE LINKED TABLE.. (if found - recursevly call self)
if ($table == false) {
$info = $this->linkInfo($field);
if ($info) {
return $this->getLink($field, $info[0], $link === false ? $info[1] : $link );
}
// no links defined.. - use borked BC method...
// use the old _ method - this shouldnt happen if called via getLinks()
if (!($p = strpos($field, '_'))) {
return false;
}
$table = substr($field, 0, $p);
return $this->getLink($field, $table);
}
$tn = is_string($table) ? $table : $table->tableName();
if (!isset($this->do->$field)) {
$this->do->raiseError("getLink: row not set $field", DB_DATAOBJECT_ERROR_NODATA);
return false;
}
// check to see if we know anything about this table..
if (empty($this->do->$field) || $this->do->$field < 0) {
return 0; // no record.
}
if ($this->cached && isset($cache[$tn.':'. $link .':'. $this->do->$field])) {
return $cache[$tn.':'. $link .':'. $this->do->$field];
}
$obj = is_string($table) ? $this->do->factory($tn) : $table;;
if (!is_a($obj,'DB_DataObject')) {
$this->do->raiseError(
"getLink:Could not find class for row $field, table $tn",
DB_DATAOBJECT_ERROR_INVALIDCONFIG);
return false;
}
// -1 or 0 -- no referenced record..
$ret = false;
if ($link) {
if ($obj->get($link, $this->do->$field)) {
$ret = $obj;
}
// this really only happens when no link config is set (old BC stuff)
} else if ($obj->get($this->do->$field)) {
$ret= $obj;
}
if ($this->cached) {
$cache[$tn.':'. $link .':'. $this->do->$field] = $ret;
}
return $ret;
}
/**
* get link information for a field or field specification
*
* alll link (and join methods accept the 'link' info ) in various ways
* string : 'field' = which field to get (uses ???.links.ini to work out what)
* array(2) : 'field', 'table:remote_col' << just like the links.ini def.
* array(3) : 'field', $dataobject, 'remote_col' (handy for joinAdd to do nested joins.)
*
* @param string|array $field or link spec to use.
* @return (false|array) array of dataobject and linked field or false.
*
*
*/
function linkInfo($field)
{
if (is_array($field)) {
if (count($field) == 3) {
// array with 3 args:
// local_col , dataobject, remote_col
return array(
$field[1],
$field[2],
$field[0]
);
}
list($table,$link) = explode(':', $field[1]);
return array(
$this->do->factory($table),
$link,
$field[0]
);
}
// work out the link.. (classic way)
$links = $this->do->links();
if (empty($links) || !is_array($links)) {
return false;
}
if (!isset($links[$field])) {
return false;
}
list($table,$link) = explode(':', $links[$field]);
//??? needed???
if ($p = strpos($field,".")) {
$field = substr($field,0,$p);
}
return array(
$this->do->factory($table),
$link,
$field
);
}
/**
* a generic geter/setter provider..
*
* provides a generic getter setter for the referenced object
* eg.
* $link->link('company_id') returns getLink for the object
* if nothing is linked (it will return an empty dataObject)
* $link->link('company_id', array(1)) - just sets the
*
* also array as the field speck supports
* $link->link(array('company_id', 'company:id'))
*
*
* @param string|array $field the field to fetch or link spec.
* @params array $args the arguments sent to the getter setter
* @return mixed true of false on set, the object on getter.
*
*/
function link($field, $args = array())
{
$info = $this->linkInfo($field);
if (!$info) {
$this->do->raiseError(
"getLink:Could not find link for row $field",
DB_DATAOBJECT_ERROR_INVALIDCONFIG);
return false;
}
$field = $info[2];
if (empty($args)) { // either an empty array or really empty....
if (!isset($this->do->$field)) {
return $info[0]; // empty dataobject.
}
$ret = $this->getLink($field);
// nothing linked -- return new object..
return ($ret === 0) ? $info[0] : $ret;
}
$assign = is_array($args) ? $args[0] : $args;
// otherwise it's a set call..
if (!is_a($assign , 'DB_DataObject')) {
if (is_numeric($assign) && is_integer($assign * 1)) {
if ($assign > 0) {
if (!$info) {
return false;
}
// check that record exists..
if (!$info[0]->get($info[1], $assign )) {
return false;
}
}
$this->do->$field = $assign ;
return true;
}
return false;
}
// otherwise we are assigning it ...
$this->do->$field = $assign->{$info[1]};
return true;
}
/**
* load related objects
*
* Generally not recommended to use this.
* The generator should support creating getter_setter methods which are better suited.
*
* Relies on <dbname>.links.ini
*
* Sets properties on the calling dataobject you can change what
* object vars the links are stored in by changeing the format parameter
*
*
* @param string format (default _%s) where %s is the table name.
* @author Tim White <tim@cyface.com>
* @access public
* @return boolean , true on success
*/
function applyLinks($format = '_%s')
{
// get table will load the options.
if ($this->do->_link_loaded) {
return true;
}
$this->do->_link_loaded = false;
$cols = $this->do->table();
$links = $this->do->links();
$loaded = array();
if ($links) {
foreach($links as $key => $match) {
list($table,$link) = explode(':', $match);
$k = sprintf($format, str_replace('.', '_', $key));
// makes sure that '.' is the end of the key;
if ($p = strpos($key,'.')) {
$key = substr($key, 0, $p);
}
$this->do->$k = $this->getLink($key, $table, $link);
if (is_object($this->do->$k)) {
$loaded[] = $k;
}
}
$this->do->_link_loaded = $loaded;
return true;
}
// this is the autonaming stuff..
// it sends the column name down to getLink and lets that sort it out..
// if there is a links file then it is not used!
// IT IS DEPRECATED!!!! - DO NOT USE
if (!is_null($links)) {
return false;
}
foreach (array_keys($cols) as $key) {
if (!($p = strpos($key, '_'))) {
continue;
}
// does the table exist.
$k =sprintf($format, $key);
$this->do->$k = $this->getLink($key);
if (is_object($this->do->$k)) {
$loaded[] = $k;
}
}
$this->do->_link_loaded = $loaded;
return true;
}
/**
* getLinkArray
* Fetch an array of related objects. This should be used in conjunction with a
* <dbname>.links.ini file configuration (see the introduction on linking for details on this).
*
* You may also use this with all parameters to specify, the column and related table.
*
* @access public
* @param string $field- either column or column.xxxxx
* @param string $table (optional) name of table to look up value in
* @param string $fkey (optional) fetchall key see DB_DataObject::fetchAll()
* @param string $fval (optional)fetchall val DB_DataObject::fetchAll()
* @param string $fval (optional) fetchall method DB_DataObject::fetchAll()
* @return array - array of results (empty array on failure)
*
* Example - Getting the related objects
*
* $person = new DataObjects_Person;
* $person->get(12);
* $children = $person->getLinkArray('children');
*
* echo 'There are ', count($children), ' descendant(s):<br />';
* foreach ($children as $child) {
* echo $child->name, '<br />';
* }
*
*/
function getLinkArray($field, $table = null, $fkey = false, $fval = false, $fmethod = false)
{
$ret = array();
if (!$table) {
$links = $this->do->links();
if (is_array($links)) {
if (!isset($links[$field])) {
// failed..
return $ret;
}
list($table,$link) = explode(':',$links[$field]);
return $this->getLinkArray($field,$table);
}
if (!($p = strpos($field,'_'))) {
return $ret;
}
return $this->getLinkArray($field,substr($field,0,$p));
}
$c = $this->do->factory($table);
if (!is_object($c) || !is_a($c,'DB_DataObject')) {
$this->do->raiseError(
"getLinkArray:Could not find class for row $field, table $table",
DB_DATAOBJECT_ERROR_INVALIDCONFIG
);
return $ret;
}
// if the user defined method list exists - use it...
if (method_exists($c, 'listFind')) {
$c->listFind($this->id);
while ($c->fetch()) {
$ret[] = clone($c);
}
return $ret;
}
return $c->fetchAll($fkey, $fval, $fmethod);
}
}

8
extlib/DB/DataObject/createTables.php Normal file → Executable file
View File

@ -16,7 +16,7 @@
// | Author: Alan Knowles <alan@akbkhome.com>
// +----------------------------------------------------------------------+
//
// $Id: createTables.php 277015 2009-03-12 05:51:03Z alan_k $
// $Id: createTables.php 315758 2011-08-30 08:11:59Z alan_k $
//
// since this version doesnt use overload,
@ -27,13 +27,17 @@ define('DB_DATAOBJECT_NO_OVERLOAD',1);
//require_once 'DB/DataObject/Generator.php';
require_once 'DB/DataObject/Generator.php';
if (php_sapi_name() != 'cli') {
PEAR::raiseError("\nERROR: You must turn use the cli sapi to run this", null, PEAR_ERROR_DIE);
}
if (!ini_get('register_argc_argv')) {
PEAR::raiseError("\nERROR: You must turn register_argc_argv On in you php.ini file for this to work\neg.\n\nregister_argc_argv = On\n\n", null, PEAR_ERROR_DIE);
exit;
}
if (!@$_SERVER['argv'][1]) {
PEAR::raiseError("\nERROR: createTable.php usage:\n\nC:\php\pear\DB\DataObjects\createTable.php example.ini\n\n", null, PEAR_ERROR_DIE);
PEAR::raiseError("\nERROR: createTable.php usage:\n\n" .$_SERVER['argv'][0] . " example.ini\n\n", null, PEAR_ERROR_DIE);
exit;
}