PageRenderTime 54ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/core/xpdo/om/xpdoobject.class.php

https://github.com/MartinGoeg/revolution
PHP | 2195 lines | 1454 code | 76 blank | 665 comment | 556 complexity | 8293f1b74213ae46fb71144cb00cb625 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.0, AGPL-1.0, LGPL-2.1, GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /*
  3. * Copyright 2006-2010 by Jason Coward <xpdo@opengeek.com>
  4. *
  5. * This file is part of xPDO.
  6. *
  7. * xPDO is free software; you can redistribute it and/or modify it under the
  8. * terms of the GNU General Public License as published by the Free Software
  9. * Foundation; either version 2 of the License, or (at your option) any later
  10. * version.
  11. *
  12. * xPDO is distributed in the hope that it will be useful, but WITHOUT ANY
  13. * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  14. * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along with
  17. * xPDO; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
  18. * Suite 330, Boston, MA 02111-1307 USA
  19. */
  20. /**
  21. * The base persistent xPDO object classes.
  22. *
  23. * This file contains the base persistent object classes, which your user-
  24. * defined classes will extend when implementing an xPDO object model.
  25. *
  26. * @package xpdo
  27. * @subpackage om
  28. */
  29. /**
  30. * The base persistent xPDO object class.
  31. *
  32. * This is the basis for the entire xPDO object model, and can also be used by a
  33. * class generator {@link xPDOGenerator}, ultimately allowing custom classes to
  34. * be user-defined in a web interface and framework-generated at runtime.
  35. *
  36. * @abstract This is an abstract class, and is not represented by an actual
  37. * table; it simply defines the member variables and functions needed for object
  38. * persistence. All xPDOObject derivatives must define both a PHP 4 style
  39. * constructor which calls a PHP 5 style __construct() method with the same
  40. * parameters. This is necessary to allow instantiation of further derived
  41. * classes without knowing the name of the class ahead of time in PHP 4. Note
  42. * that this does not meet E_STRICT compliance in PHP 5, but is the only sane
  43. * way to achieve consistency between the PHP 4 and 5 inheritence models.
  44. *
  45. * @package xpdo
  46. * @subpackage om
  47. */
  48. class xPDOObject {
  49. /**
  50. * A convenience reference to the xPDO object.
  51. * @var xPDO
  52. * @access public
  53. */
  54. public $xpdo= null;
  55. /**
  56. * Name of the data source container the object belongs to.
  57. * @var string
  58. * @access public
  59. */
  60. public $container= null;
  61. /**
  62. * Names of the fields in the data table, fully-qualified with a table name.
  63. *
  64. * NOTE: For use in table joins to qualify fields with the same name.
  65. *
  66. * @var array
  67. * @access public
  68. */
  69. public $fieldNames= null;
  70. /**
  71. * The actual class name of an instance.
  72. * @var string
  73. */
  74. public $_class= null;
  75. /**
  76. * The package the class is a part of.
  77. * @var string
  78. */
  79. public $_package= null;
  80. /**
  81. * An alias for this instance of the class.
  82. * @var string
  83. */
  84. public $_alias= null;
  85. /**
  86. * The primary key field (or an array of primary key fields) for this object.
  87. * @var string|array
  88. * @access public
  89. */
  90. public $_pk= null;
  91. /**
  92. * The php native type of the primary key field.
  93. *
  94. * NOTE: Will be an array if multiple primary keys are specified for the object.
  95. *
  96. * @var string|array
  97. * @access public
  98. */
  99. public $_pktype= null;
  100. /**
  101. * Name of the actual table representing this class.
  102. * @var string
  103. * @access public
  104. */
  105. public $_table= null;
  106. /**
  107. * An array of meta data for the table.
  108. * @var string
  109. * @access public
  110. */
  111. public $_tableMeta= null;
  112. /**
  113. * An array of field names that have been modified.
  114. * @var array
  115. * @access public
  116. */
  117. public $_dirty= array ();
  118. /**
  119. * An array of field names that have not been loaded from the source.
  120. * @var array
  121. * @access public
  122. */
  123. public $_lazy= array ();
  124. /**
  125. * An array of key-value pairs representing the fields of the instance.
  126. * @var array
  127. * @access public
  128. */
  129. public $_fields= array ();
  130. /**
  131. * An array of metadata definitions for each field in the class.
  132. * @var array
  133. * @access public
  134. */
  135. public $_fieldMeta= array ();
  136. /**
  137. * An array of aggregate foreign key relationships for the class.
  138. * @var array
  139. * @access public
  140. */
  141. public $_aggregates= array ();
  142. /**
  143. * An array of composite foreign key relationships for the class.
  144. * @var array
  145. * @access public
  146. */
  147. public $_composites= array ();
  148. /**
  149. * An array of object instances related to this object instance.
  150. * @var array
  151. * @access public
  152. */
  153. public $_relatedObjects= array ();
  154. /**
  155. * A validator object responsible for this object instance.
  156. * @var xPDOValidator
  157. * @access public
  158. */
  159. public $_validator = null;
  160. /**
  161. * An array of validation rules for this object instance.
  162. * @var array
  163. * @access public
  164. */
  165. public $_validationRules = array();
  166. /**
  167. * An array of field names that have been already validated.
  168. * @var array
  169. * @access public
  170. */
  171. public $_validated= array ();
  172. /**
  173. * Indicates if the validation map has been loaded.
  174. * @var boolean
  175. * @access public
  176. */
  177. public $_validationLoaded= false;
  178. /**
  179. * Indicates if the instance is transient (and thus new).
  180. * @var boolean
  181. * @access public
  182. */
  183. public $_new= true;
  184. /**
  185. * Indicates the cacheability of the instance.
  186. * @var boolean
  187. */
  188. public $_cacheFlag= true;
  189. /**
  190. * A collection of various options that can be used on the instance.
  191. * @var array
  192. */
  193. public $_options= array();
  194. /**
  195. * Responsible for loading a result set from the database.
  196. *
  197. * @static
  198. * @param xPDO &$xpdo A valid xPDO instance.
  199. * @param string $className Name of the class.
  200. * @param mixed $criteria A valid primary key, criteria array, or xPDOCriteria instance.
  201. * @return PDOStatement A reference to a PDOStatement representing the
  202. * result set.
  203. */
  204. public static function & _loadRows(& $xpdo, $className, $criteria) {
  205. $rows= null;
  206. if ($criteria->prepare()) {
  207. if ($xpdo->getDebug() === true) $xpdo->log(xPDO::LOG_LEVEL_DEBUG, "Attempting to execute query using PDO statement object: " . print_r($criteria->sql, true) . print_r($criteria->bindings, true));
  208. $tstart= $xpdo->getMicroTime();
  209. if (!$criteria->stmt->execute()) {
  210. $tend= $xpdo->getMicroTime();
  211. $totaltime= $tend - $tstart;
  212. $xpdo->queryTime= $xpdo->queryTime + $totaltime;
  213. $xpdo->executedQueries= $xpdo->executedQueries + 1;
  214. $errorInfo= $criteria->stmt->errorInfo();
  215. $xpdo->log(xPDO::LOG_LEVEL_ERROR, 'Error ' . $criteria->stmt->errorCode() . " executing statement: \n" . print_r($errorInfo, true));
  216. if ($errorInfo[1] == '1146' || $errorInfo[1] == '1') {
  217. if ($xpdo->getManager() && $xpdo->manager->createObjectContainer($className)) {
  218. $tstart= $xpdo->getMicroTime();
  219. if (!$criteria->stmt->execute()) {
  220. $xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $criteria->stmt->errorCode() . " executing statement: \n" . print_r($criteria->stmt->errorInfo(), true));
  221. }
  222. $tend= $xpdo->getMicroTime();
  223. $totaltime= $tend - $tstart;
  224. $xpdo->queryTime= $xpdo->queryTime + $totaltime;
  225. $xpdo->executedQueries= $xpdo->executedQueries + 1;
  226. } else {
  227. $xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $xpdo->errorCode() . " attempting to create object container for class {$className}:\n" . print_r($xpdo->errorInfo(), true));
  228. }
  229. }
  230. }
  231. $rows= & $criteria->stmt;
  232. } else {
  233. $errorInfo = $xpdo->errorInfo();
  234. $xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error preparing statement for query: {$criteria->sql} - " . print_r($errorInfo, true));
  235. if ($errorInfo[1] == '1146' || $errorInfo[1] == '1') {
  236. if ($xpdo->getManager() && $xpdo->manager->createObjectContainer($className)) {
  237. if (!$criteria->prepare()) {
  238. $xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error preparing statement for query: {$criteria->sql} - " . print_r($errorInfo, true));
  239. } else {
  240. $tstart= $xpdo->getMicroTime();
  241. if (!$criteria->stmt->execute()) {
  242. $xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $criteria->stmt->errorCode() . " executing statement: \n" . print_r($criteria->stmt->errorInfo(), true));
  243. }
  244. $tend= $xpdo->getMicroTime();
  245. $totaltime= $tend - $tstart;
  246. $xpdo->queryTime= $xpdo->queryTime + $totaltime;
  247. $xpdo->executedQueries= $xpdo->executedQueries + 1;
  248. }
  249. } else {
  250. $xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $xpdo->errorCode() . " attempting to create object container for class {$className}:\n" . print_r($xpdo->errorInfo(), true));
  251. }
  252. }
  253. }
  254. return $rows;
  255. }
  256. /**
  257. * Loads an instance from an associative array.
  258. *
  259. * @static
  260. * @param xPDO &$xpdo A valid xPDO instance.
  261. * @param string $className Name of the class.
  262. * @param mixed $criteria A valid xPDOQuery instance or relation alias.
  263. * @param array $row The associative array containing the instance data.
  264. * @return xPDOObject A new xPDOObject derivative representing a data row.
  265. */
  266. public static function _loadInstance(& $xpdo, $className, $criteria, $row) {
  267. $rowPrefix= '';
  268. if (is_object($criteria) && $criteria instanceof xPDOQuery) {
  269. $alias = $criteria->getAlias();
  270. $actualClass = $criteria->getClass();
  271. } elseif (is_string($criteria) && !empty($criteria)) {
  272. $alias = $criteria;
  273. $actualClass = $className;
  274. } else {
  275. $alias = $className;
  276. $actualClass= $className;
  277. }
  278. if (isset($row["{$className}_class_key"])) {
  279. $actualClass= $row["{$className}_class_key"];
  280. $rowPrefix= $className . '_';
  281. }
  282. elseif (isset ($row["{$alias}_class_key"])) {
  283. $actualClass= $row["{$alias}_class_key"];
  284. $rowPrefix= $alias . '_';
  285. }
  286. elseif (isset ($row['class_key'])) {
  287. $actualClass= $row['class_key'];
  288. }
  289. $instance= $xpdo->newObject($actualClass);
  290. if (is_object($instance) && $instance instanceof xPDOObject) {
  291. if (strpos(strtolower(key($row)), strtolower($alias . '_')) === 0) {
  292. $rowPrefix= $alias . '_';
  293. }
  294. elseif (strpos(strtolower(key($row)), strtolower($className . '_')) === 0) {
  295. $rowPrefix= $className . '_';
  296. }
  297. else {
  298. $pk = $xpdo->getPK($actualClass);
  299. if (is_array($pk)) $pk = reset($pk);
  300. if (isset($row["{$alias}_{$pk}"])) {
  301. $rowPrefix= $alias . '_';
  302. }
  303. elseif ($actualClass !== $className && $actualClass !== $alias && isset($row["{$actualClass}_{$pk}"])) {
  304. $rowPrefix= $actualClass . '_';
  305. }
  306. elseif ($className !== $alias && isset($row["{$className}_{$pk}"])) {
  307. $rowPrefix= $className . '_';
  308. }
  309. }
  310. if (!$instance instanceof $className) {
  311. $xpdo->log(xPDO::LOG_LEVEL_ERROR, "Instantiated a derived class {$actualClass} that is not a subclass of the requested class {$className}");
  312. }
  313. $instance->_lazy= array_keys($instance->_fields);
  314. $instance->fromArray($row, $rowPrefix, true, true);
  315. $instance->_dirty= array ();
  316. $instance->_new= false;
  317. }
  318. return $instance;
  319. }
  320. /**
  321. * Responsible for loading an instance into a collection.
  322. *
  323. * @static
  324. * @param xPDO &$xpdo A valid xPDO instance.
  325. * @param array &$objCollection The collection to load the instance into.
  326. * @param string $className Name of the class.
  327. * @param mixed $criteria A valid primary key, criteria array, or xPDOCriteria instance.
  328. * @param boolean|integer $cacheFlag Indicates if the objects should be cached and
  329. * optionally, by specifying an integer value, for how many seconds.
  330. */
  331. public static function _loadCollectionInstance(xPDO & $xpdo, array & $objCollection, $className, $criteria, $row, $fromCache, $cacheFlag=true) {
  332. $loaded = false;
  333. if ($obj= xPDOObject :: _loadInstance($xpdo, $className, $criteria, $row)) {
  334. if (($cacheKey= $obj->getPrimaryKey()) && !$obj->isLazy()) {
  335. if (is_array($cacheKey)) {
  336. $pkval= implode('-', $cacheKey);
  337. } else {
  338. $pkval= $cacheKey;
  339. }
  340. if ($xpdo->getOption(xPDO::OPT_CACHE_DB_COLLECTIONS, array(), 1) == 2 && $xpdo->_cacheEnabled && $cacheFlag) {
  341. if (!$fromCache) {
  342. $pkCriteria = $xpdo->newQuery($className, $cacheKey, $cacheFlag);
  343. $xpdo->toCache($pkCriteria, $obj, $cacheFlag);
  344. } else {
  345. $obj->_cacheFlag= true;
  346. }
  347. }
  348. $objCollection[$pkval]= $obj;
  349. $loaded = true;
  350. } else {
  351. $objCollection[]= $obj;
  352. $loaded = true;
  353. }
  354. }
  355. return $loaded;
  356. }
  357. /**
  358. * Load an instance of an xPDOObject or derivative class.
  359. *
  360. * @static
  361. * @param xPDO &$xpdo A valid xPDO instance.
  362. * @param string $className Name of the class.
  363. * @param mixed $criteria A valid primary key, criteria array, or
  364. * xPDOCriteria instance.
  365. * @param boolean|integer $cacheFlag Indicates if the objects should be
  366. * cached and optionally, by specifying an integer value, for how many
  367. * seconds.
  368. * @return object|null An instance of the requested class, or null if it
  369. * could not be instantiated.
  370. */
  371. public static function load(xPDO & $xpdo, $className, $criteria, $cacheFlag= true) {
  372. $instance= null;
  373. $fromCache= false;
  374. if ($className= $xpdo->loadClass($className)) {
  375. if (!is_object($criteria)) {
  376. $criteria= $xpdo->getCriteria($className, $criteria, $cacheFlag);
  377. }
  378. if (is_object($criteria)) {
  379. $criteria = $xpdo->addDerivativeCriteria($className, $criteria);
  380. $row= null;
  381. if ($xpdo->_cacheEnabled && $criteria->cacheFlag && $cacheFlag) {
  382. $row= $xpdo->fromCache($criteria, $className);
  383. }
  384. if ($row === null || !is_array($row)) {
  385. if ($rows= xPDOObject :: _loadRows($xpdo, $className, $criteria)) {
  386. $row= $rows->fetch(PDO::FETCH_ASSOC);
  387. $rows->closeCursor();
  388. }
  389. } else {
  390. $fromCache= true;
  391. }
  392. if (!is_array($row)) {
  393. if ($xpdo->getDebug() === true) $xpdo->log(xPDO::LOG_LEVEL_DEBUG, "Fetched empty result set from statement: " . print_r($criteria->sql, true) . " with bindings: " . print_r($criteria->bindings, true));
  394. } else {
  395. $instance= xPDOObject :: _loadInstance($xpdo, $className, $criteria, $row);
  396. if (is_object($instance)) {
  397. if (!$fromCache && $cacheFlag && $xpdo->_cacheEnabled) {
  398. $xpdo->toCache($criteria, $instance, $cacheFlag);
  399. if ($xpdo->getOption(xPDO::OPT_CACHE_DB_OBJECTS_BY_PK) && ($cacheKey= $instance->getPrimaryKey()) && !$instance->isLazy()) {
  400. $pkCriteria = $xpdo->newQuery($className, $cacheKey, $cacheFlag);
  401. $xpdo->toCache($pkCriteria, $instance, $cacheFlag);
  402. }
  403. }
  404. if ($xpdo->getDebug() === true) $xpdo->log(xPDO::LOG_LEVEL_DEBUG, "Loaded object instance: " . print_r($instance->toArray('', true), true));
  405. }
  406. }
  407. } else {
  408. $xpdo->log(xPDO::LOG_LEVEL_ERROR, 'No valid statement could be found in or generated from the given criteria.');
  409. }
  410. } else {
  411. $xpdo->log(xPDO::LOG_LEVEL_ERROR, 'Invalid class specified: ' . $className);
  412. }
  413. return $instance;
  414. }
  415. /**
  416. * Load a collection of xPDOObject instances.
  417. *
  418. * @static
  419. * @param xPDO &$xpdo A valid xPDO instance.
  420. * @param string $className Name of the class.
  421. * @param mixed $criteria A valid primary key, criteria array, or xPDOCriteria instance.
  422. * @param boolean|integer $cacheFlag Indicates if the objects should be
  423. * cached and optionally, by specifying an integer value, for how many
  424. * seconds.
  425. * @return array An array of xPDOObject instances or an empty array if no instances are loaded.
  426. */
  427. public static function loadCollection(xPDO & $xpdo, $className, $criteria= null, $cacheFlag= true) {
  428. $objCollection= array ();
  429. $fromCache = false;
  430. if (!$className= $xpdo->loadClass($className)) return $objCollection;
  431. $rows= false;
  432. $fromCache= false;
  433. $collectionCaching = (integer) $xpdo->getOption(xPDO::OPT_CACHE_DB_COLLECTIONS, array(), 1);
  434. if (!is_object($criteria)) {
  435. $criteria= $xpdo->getCriteria($className, $criteria, $cacheFlag);
  436. }
  437. if (is_object($criteria)) {
  438. $criteria = $xpdo->addDerivativeCriteria($className, $criteria);
  439. }
  440. if ($collectionCaching > 0 && $xpdo->_cacheEnabled && $cacheFlag) {
  441. $rows= $xpdo->fromCache($criteria);
  442. $fromCache = (is_array($rows) && !empty($rows));
  443. }
  444. if (!$fromCache && is_object($criteria)) {
  445. $rows= xPDOObject :: _loadRows($xpdo, $className, $criteria);
  446. }
  447. if (is_array ($rows)) {
  448. foreach ($rows as $row) {
  449. xPDOObject :: _loadCollectionInstance($xpdo, $objCollection, $className, $criteria, $row, $fromCache, $cacheFlag);
  450. }
  451. } elseif (is_object($rows)) {
  452. $cacheRows = array();
  453. while ($row = $rows->fetch(PDO::FETCH_ASSOC)) {
  454. xPDOObject :: _loadCollectionInstance($xpdo, $objCollection, $className, $criteria, $row, $fromCache, $cacheFlag);
  455. if ($collectionCaching > 0 && $xpdo->_cacheEnabled && $cacheFlag && !$fromCache) $cacheRows[] = $row;
  456. }
  457. if ($collectionCaching > 0 && $xpdo->_cacheEnabled && $cacheFlag && !$fromCache) $rows =& $cacheRows;
  458. }
  459. if (!$fromCache && $xpdo->_cacheEnabled && $collectionCaching > 0 && $cacheFlag && !empty($rows)) {
  460. $xpdo->toCache($criteria, $rows, $cacheFlag);
  461. }
  462. return $objCollection;
  463. }
  464. /**
  465. * Load a collection of xPDOObject instances and a graph of related objects.
  466. *
  467. * @static
  468. * @param xPDO &$xpdo A valid xPDO instance.
  469. * @param string $className Name of the class.
  470. * @param string|array $graph A related object graph in array or JSON
  471. * format, e.g. array('relationAlias'=>array('subRelationAlias'=>array()))
  472. * or {"relationAlias":{"subRelationAlias":{}}}. Note that the empty arrays
  473. * are necessary in order for the relation to be recognized.
  474. * @param mixed $criteria A valid primary key, criteria array, or xPDOCriteria instance.
  475. * @param boolean|integer $cacheFlag Indicates if the objects should be
  476. * cached and optionally, by specifying an integer value, for how many
  477. * seconds.
  478. * @return array An array of xPDOObject instances or an empty array if no instances are loaded.
  479. */
  480. public static function loadCollectionGraph(xPDO & $xpdo, $className, $graph, $criteria, $cacheFlag) {
  481. $objCollection = array();
  482. if ($query= $xpdo->newQuery($className, $criteria, $cacheFlag)) {
  483. $query = $xpdo->addDerivativeCriteria($className, $query);
  484. $query->bindGraph($graph);
  485. $rows = array();
  486. $fromCache = false;
  487. $collectionCaching = (integer) $xpdo->getOption(xPDO::OPT_CACHE_DB_COLLECTIONS, array(), 1);
  488. if ($collectionCaching > 0 && $xpdo->_cacheEnabled && $cacheFlag) {
  489. $rows= $xpdo->fromCache($query);
  490. $fromCache = !empty($rows);
  491. }
  492. if (!$fromCache) {
  493. $stmt= $query->prepare();
  494. if ($stmt && $stmt->execute()) {
  495. $objCollection= $query->hydrateGraph($stmt, $cacheFlag);
  496. }
  497. } elseif (!empty($rows)) {
  498. $objCollection= $query->hydrateGraph($rows, $cacheFlag);
  499. }
  500. }
  501. return $objCollection;
  502. }
  503. /**
  504. * Get a set of column names from an xPDOObject for use in SQL queries.
  505. *
  506. * @static
  507. * @param xPDO &$xpdo A reference to an initialized xPDO instance.
  508. * @param string $className The class name to get columns from.
  509. * @param string $tableAlias An optional alias for the table in the query.
  510. * @param string $columnPrefix An optional prefix to prepend to each column name.
  511. * @param array $columns An optional array of field names to include or exclude
  512. * (include is default behavior).
  513. * @param boolean $exclude Determines if any specified columns should be included
  514. * or excluded from the set of results.
  515. * @return string A comma-delimited list of the field names for use in a SELECT clause.
  516. */
  517. public static function getSelectColumns(xPDO & $xpdo, $className, $tableAlias= '', $columnPrefix= '', $columns= array (), $exclude= false) {
  518. $columnarray= array ();
  519. $aColumns= $xpdo->getFields($className);
  520. if ($aColumns) {
  521. if (!empty ($tableAlias)) {
  522. $tableAlias= $xpdo->escape($tableAlias);
  523. $tableAlias.= '.';
  524. }
  525. foreach (array_keys($aColumns) as $k) {
  526. if ($exclude && in_array($k, $columns)) {
  527. continue;
  528. }
  529. elseif (empty ($columns)) {
  530. $columnarray[$k]= "{$tableAlias}" . $xpdo->escape($k);
  531. }
  532. elseif ($exclude || in_array($k, $columns)) {
  533. $columnarray[$k]= "{$tableAlias}" . $xpdo->escape($k);
  534. } else {
  535. continue;
  536. }
  537. if (!empty ($columnPrefix)) {
  538. $columnarray[$k]= $columnarray[$k] . " AS " . $xpdo->escape("{$columnPrefix}{$k}");
  539. }
  540. }
  541. }
  542. return implode(', ', $columnarray);
  543. }
  544. /**
  545. * Constructor
  546. *
  547. * Do not call the constructor directly; see {@link xPDO::newObject()}.
  548. *
  549. * All derivatives of xPDOObject must redeclare this method, and must call
  550. * the parent method explicitly before any additional logic is executed, e.g.
  551. *
  552. * <code>
  553. * public function __construct(xPDO & $xpdo) {
  554. * parent :: __construct($xpdo);
  555. * // Any additional constructor tasks here
  556. * }
  557. * </code>
  558. *
  559. * @access public
  560. * @param xPDO &$xpdo A reference to a valid xPDO instance.
  561. * @return xPDOObject
  562. */
  563. public function __construct(xPDO & $xpdo) {
  564. $this->container= $xpdo->config['dbname'];
  565. $this->_class= get_class($this);
  566. $pos= strrpos($this->_class, '_');
  567. if ($pos !== false && substr($this->_class, $pos + 1) == $xpdo->config['dbtype']) {
  568. $this->_class= substr($this->_class, 0, $pos);
  569. }
  570. $this->_package= $xpdo->getPackage($this->_class);
  571. $this->_alias= $this->_class;
  572. $this->_table= $xpdo->getTableName($this->_class);
  573. $this->_tableMeta= $xpdo->getTableMeta($this->_class);
  574. $this->_fields= $xpdo->getFields($this->_class);
  575. $this->_fieldMeta= $xpdo->getFieldMeta($this->_class);
  576. $this->_aggregates= $xpdo->getAggregates($this->_class);
  577. $this->_composites= $xpdo->getComposites($this->_class);
  578. $this->_options[xPDO::OPT_CALLBACK_ON_REMOVE]= isset ($xpdo->config[xPDO::OPT_CALLBACK_ON_REMOVE]) && !empty($xpdo->config[xPDO::OPT_CALLBACK_ON_REMOVE]) ? $xpdo->config[xPDO::OPT_CALLBACK_ON_REMOVE] : null;
  579. $this->_options[xPDO::OPT_CALLBACK_ON_SAVE]= isset ($xpdo->config[xPDO::OPT_CALLBACK_ON_SAVE]) && !empty($xpdo->config[xPDO::OPT_CALLBACK_ON_SAVE]) ? $xpdo->config[xPDO::OPT_CALLBACK_ON_SAVE] : null;
  580. $this->_options[xPDO::OPT_HYDRATE_RELATED_OBJECTS]= isset ($xpdo->config[xPDO::OPT_HYDRATE_RELATED_OBJECTS]) && $xpdo->config[xPDO::OPT_HYDRATE_RELATED_OBJECTS];
  581. $this->_options[xPDO::OPT_HYDRATE_ADHOC_FIELDS]= isset ($xpdo->config[xPDO::OPT_HYDRATE_ADHOC_FIELDS]) && $xpdo->config[xPDO::OPT_HYDRATE_ADHOC_FIELDS];
  582. $this->_options[xPDO::OPT_HYDRATE_FIELDS]= isset ($xpdo->config[xPDO::OPT_HYDRATE_FIELDS]) && $xpdo->config[xPDO::OPT_HYDRATE_FIELDS];
  583. $this->_options[xPDO::OPT_ON_SET_STRIPSLASHES]= isset ($xpdo->config[xPDO::OPT_ON_SET_STRIPSLASHES]) && $xpdo->config[xPDO::OPT_ON_SET_STRIPSLASHES];
  584. $this->_options[xPDO::OPT_VALIDATE_ON_SAVE]= isset ($xpdo->config[xPDO::OPT_VALIDATE_ON_SAVE]) && $xpdo->config[xPDO::OPT_VALIDATE_ON_SAVE];
  585. $this->_options[xPDO::OPT_VALIDATOR_CLASS]= isset ($xpdo->config[xPDO::OPT_VALIDATOR_CLASS]) ? $xpdo->config[xPDO::OPT_VALIDATOR_CLASS] : '';
  586. $classVars= array ();
  587. if ($relatedObjs= array_merge($this->_aggregates, $this->_composites)) {
  588. if ($this->_options[xPDO::OPT_HYDRATE_RELATED_OBJECTS]) $classVars= get_object_vars($this);
  589. foreach ($relatedObjs as $aAlias => $aMeta) {
  590. if (!array_key_exists($aAlias, $this->_relatedObjects)) {
  591. if ($aMeta['cardinality'] == 'many') {
  592. $this->_relatedObjects[$aAlias]= array ();
  593. }
  594. else {
  595. $this->_relatedObjects[$aAlias]= null;
  596. }
  597. }
  598. if ($this->_options[xPDO::OPT_HYDRATE_RELATED_OBJECTS] && !array_key_exists($aAlias, $classVars)) {
  599. $this->$aAlias= & $this->_relatedObjects[$aAlias];
  600. $classVars[$aAlias]= 1;
  601. }
  602. }
  603. }
  604. if ($this->_options[xPDO::OPT_HYDRATE_FIELDS]) {
  605. if (!$this->_options[xPDO::OPT_HYDRATE_RELATED_OBJECTS]) $classVars= get_object_vars($this);
  606. foreach ($this->_fields as $fldKey => $fldVal) {
  607. if (!array_key_exists($fldKey, $classVars)) {
  608. $this->$fldKey= & $this->_fields[$fldKey];
  609. }
  610. }
  611. }
  612. $this->setDirty();
  613. $this->xpdo= & $xpdo;
  614. }
  615. /**
  616. * Get an option value for this instance.
  617. *
  618. * @param string $key The option key to retrieve a value from.
  619. * @return mixed The value of the option or null if it is not set.
  620. */
  621. public function getOption($key) {
  622. $option= null;
  623. if (isset($this->_options[$key])) {
  624. $option= $this->_options[$key];
  625. }
  626. return $option;
  627. }
  628. /**
  629. * Set an option value for this instance.
  630. *
  631. * @param string $key The option key to set a value for.
  632. * @param mixed $value A value to assign to the option.
  633. */
  634. public function setOption($key, $value) {
  635. $this->_options[$key]= $value;
  636. }
  637. /**
  638. * Set a field value by the field key or name.
  639. *
  640. * @todo Define and implement field validation.
  641. *
  642. * @param string $k The field key or name.
  643. * @param mixed $v The value to set the field to.
  644. * @param string|callable $vType A string indicating the format of the
  645. * provided value parameter, or a callable function that should be used to
  646. * set the field value, overriding the default behavior.
  647. * @return boolean Determines whether the value was set successfully and was
  648. * determined to be dirty (i.e. different from the previous value).
  649. */
  650. public function set($k, $v= null, $vType= '') {
  651. $set= false;
  652. $callback= '';
  653. $callable= !empty($vType) && is_callable($vType, false, $callback) ? true : false;
  654. $oldValue= null;
  655. if (is_string($k) && !empty($k)) {
  656. if (array_key_exists($k, $this->_fieldMeta)) {
  657. $oldValue= $this->_fields[$k];
  658. if (isset ($this->_fieldMeta[$k]['index']) && $this->_fieldMeta[$k]['index'] === 'pk' && isset ($this->_fieldMeta[$k]['generated'])) {
  659. if (!$this->_fieldMeta[$k]['generated'] === 'callback') {
  660. return false;
  661. }
  662. }
  663. if ($callable && $callback) {
  664. $set = $callback($k, $v, $this);
  665. } else {
  666. if (is_string($v) && isset($this->_options[xPDO::OPT_ON_SET_STRIPSLASHES]) && (boolean) $this->_options[xPDO::OPT_ON_SET_STRIPSLASHES])
  667. $v= stripslashes($v);
  668. if ($oldValue !== $v) {
  669. //type validation
  670. $phptype= $this->_fieldMeta[$k]['phptype'];
  671. $dbtype= $this->_fieldMeta[$k]['dbtype'];
  672. $allowNull= isset($this->_fieldMeta[$k]['null']) ? (boolean) $this->_fieldMeta[$k]['null'] : true;
  673. if ($v === null) {
  674. if ($allowNull) {
  675. $this->_fields[$k]= null;
  676. $set= true;
  677. } else {
  678. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "{$this->_class}: Attempt to set NOT NULL field {$k} to NULL");
  679. }
  680. }
  681. else {
  682. switch ($phptype) {
  683. case 'timestamp' :
  684. case 'datetime' :
  685. $ts= false;
  686. if (strtolower($dbtype) == 'int' || strtolower($dbtype) == 'integer') {
  687. if (strtolower($vType) == 'integer' || is_int($v) || $v == '0') {
  688. $ts= (integer) $v;
  689. } else {
  690. $ts= strtotime($v);
  691. }
  692. if ($ts === false) {
  693. $ts= 0;
  694. }
  695. $this->_fields[$k]= $ts;
  696. $set= true;
  697. } else {
  698. if ($vType == 'utc' || in_array($v, $this->xpdo->driver->_currentTimestamps) || $v === '0000-00-00 00:00:00') {
  699. $this->_fields[$k]= (string) $v;
  700. $set= true;
  701. } else {
  702. if (strtolower($vType) == 'integer' || is_int($v)) {
  703. $ts= intval($v);
  704. } elseif (is_string($v) && !empty($v)) {
  705. $ts= strtotime($v);
  706. }
  707. if ($ts !== false) {
  708. $this->_fields[$k]= strftime('%Y-%m-%d %H:%M:%S', $ts);
  709. $set= true;
  710. }
  711. }
  712. }
  713. break;
  714. case 'date' :
  715. if (strtolower($dbtype) == 'int' || strtolower($dbtype) == 'integer') {
  716. if (strtolower($vType) == 'integer' || is_int($v) || $v == '0') {
  717. $ts= (integer) $v;
  718. } else {
  719. $ts= strtotime($v);
  720. }
  721. if ($ts === false) {
  722. $ts= 0;
  723. }
  724. $this->_fields[$k]= $ts;
  725. $set= true;
  726. } else {
  727. if ($vType == 'utc' || in_array($v, $this->xpdo->driver->_currentDates) || $v === '0000-00-00') {
  728. $this->_fields[$k]= $v;
  729. $set= true;
  730. } else {
  731. if (strtolower($vType) == 'integer' || is_int($v)) {
  732. $ts= intval($v);
  733. } elseif (is_string($v) && !empty($v)) {
  734. $ts= strtotime($v);
  735. }
  736. $ts= strtotime($v);
  737. if ($ts !== false) {
  738. $this->_fields[$k]= strftime('%Y-%m-%d', $ts);
  739. $set= true;
  740. }
  741. }
  742. }
  743. break;
  744. case 'boolean' :
  745. $this->_fields[$k]= intval($v);
  746. $set= true;
  747. break;
  748. case 'integer' :
  749. $this->_fields[$k]= intval($v);
  750. $set= true;
  751. break;
  752. case 'array' :
  753. if (is_object($v) && $v instanceof xPDOObject) {
  754. $v = $v->toArray();
  755. }
  756. if (is_array($v)) {
  757. $this->_fields[$k]= serialize($v);
  758. $set= true;
  759. }
  760. break;
  761. case 'json' :
  762. if (is_object($v) && $v instanceof xPDOObject) {
  763. $v = $v->toArray();
  764. }
  765. if (is_string($v)) {
  766. $v= $this->xpdo->fromJSON($v, true);
  767. }
  768. if (is_array($v)) {
  769. $this->_fields[$k]= $this->xpdo->toJSON($v);
  770. $set= true;
  771. }
  772. break;
  773. default :
  774. $this->_fields[$k]= $v;
  775. $set= true;
  776. }
  777. }
  778. }
  779. }
  780. } elseif ($this->_options[xPDO::OPT_HYDRATE_ADHOC_FIELDS]) {
  781. $oldValue= isset($this->_fields[$k]) ? $this->_fields[$k] : null;
  782. if ($callable) {
  783. $set = $callback($k, $v, $this);
  784. } else {
  785. $this->_fields[$k]= $v;
  786. $set= true;
  787. }
  788. }
  789. if ($set && $oldValue !== $this->_fields[$k]) {
  790. $this->setDirty($k);
  791. } else {
  792. $set= false;
  793. }
  794. if ($set && $this->_options[xPDO::OPT_HYDRATE_FIELDS] && !isset ($this->$k)) {
  795. $this->$k= & $this->_fields[$k];
  796. }
  797. } else {
  798. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, 'xPDOObject - Called set() with an invalid field name: ' . print_r($k, 1));
  799. }
  800. return $set;
  801. }
  802. /**
  803. * Get a field value (or a set of values) by the field key(s) or name(s).
  804. *
  805. * Warning: do not use the $format parameter if retrieving multiple values of
  806. * different types, as the format string will be applied to all types, most
  807. * likely with unpredicatable results. Optionally, you can supply an associate
  808. * array of format strings with the field key as the key for the format array.
  809. *
  810. * @param string|array $k A string (or an array of strings) representing the field
  811. * key or name.
  812. * @param string|array $format An optional variable (or an array of variables) to
  813. * format the return value(s).
  814. * @param mixed $formatTemplate An additional optional variable that can be used in
  815. * formatting the return value(s).
  816. * @return mixed The value(s) of the field(s) requested.
  817. */
  818. public function get($k, $format = null, $formatTemplate= null) {
  819. $value= null;
  820. if (is_array($k)) {
  821. if ($this->isLazy()) {
  822. $this->_loadFieldData($k);
  823. }
  824. foreach ($k as $key) {
  825. if (array_key_exists($key, $this->_fields)) {
  826. if (is_array($format) && isset ($format[$key])) {
  827. $formatTpl= null;
  828. if (is_array ($formatTemplate) && isset ($formatTemplate[$key])) {
  829. $formatTpl= $formatTemplate[$key];
  830. }
  831. $value[$key]= $this->get($key, $format[$key], $formatTpl);
  832. } elseif (!empty ($format) && is_string($format)) {
  833. $value[$key]= $this->get($key, $format, $formatTemplate);
  834. } else {
  835. $value[$key]= $this->get($key);
  836. }
  837. }
  838. }
  839. } elseif (is_string($k) && !empty($k)) {
  840. if (array_key_exists($k, $this->_fields)) {
  841. if ($this->isLazy($k)) {
  842. $this->_loadFieldData($k);
  843. }
  844. $dbType= $this->_getDataType($k);
  845. $fieldType= $this->_getPHPType($k);
  846. $value= $this->_fields[$k];
  847. if ($value !== null) {
  848. switch ($fieldType) {
  849. case 'boolean' :
  850. $value= (boolean) $value;
  851. break;
  852. case 'integer' :
  853. $value= intval($value);
  854. if (is_string($format) && !empty ($format)) {
  855. if (strpos($format, 're:') === 0) {
  856. if (!empty ($formatTemplate) && is_string($formatTemplate)) {
  857. $value= preg_replace(substr($format, 3), $formatTemplate, $value);
  858. }
  859. } else {
  860. $value= sprintf($format, $value);
  861. }
  862. }
  863. break;
  864. case 'float' :
  865. $value= (float) $value;
  866. if (is_string($format) && !empty ($format)) {
  867. if (strpos($format, 're:') === 0) {
  868. if (!empty ($formatTemplate) && is_string($formatTemplate)) {
  869. $value= preg_replace(substr($format, 3), $formatTemplate, $value);
  870. }
  871. } else {
  872. $value= sprintf($format, $value);
  873. }
  874. }
  875. break;
  876. case 'timestamp' :
  877. case 'datetime' :
  878. if ($dbType == 'int' || $dbType == 'integer' || $dbType == 'INT' || $dbType == 'INTEGER') {
  879. $ts= intval($value);
  880. } elseif (in_array($value, $this->xpdo->driver->_currentTimestamps)) {
  881. $ts= time();
  882. } else {
  883. $ts= strtotime($value);
  884. }
  885. if ($ts !== false && !empty($value)) {
  886. if (is_string($format) && !empty ($format)) {
  887. if (strpos($format, 're:') === 0) {
  888. $value= date('Y-m-d H:M:S', $ts);
  889. if (!empty ($formatTemplate) && is_string($formatTemplate)) {
  890. $value= preg_replace(substr($format, 3), $formatTemplate, $value);
  891. }
  892. } elseif (strpos($format, '%') === false) {
  893. $value= date($format, $ts);
  894. } else {
  895. $value= strftime($format, $ts);
  896. }
  897. } else {
  898. $value= strftime('%Y-%m-%d %H:%M:%S', $ts);
  899. }
  900. }
  901. break;
  902. case 'date' :
  903. if ($dbType == 'int' || $dbType == 'integer' || $dbType == 'INT' || $dbType == 'INTEGER') {
  904. $ts= intval($value);
  905. } elseif (in_array($value, $this->xpdo->driver->_currentDates)) {
  906. $ts= time();
  907. } else {
  908. $ts= strtotime($value);
  909. }
  910. if ($ts !== false && !empty($value)) {
  911. if (is_string($format) && !empty ($format)) {
  912. if (strpos($format, 're:') === 0) {
  913. $value= strftime('%Y-%m-%d', $ts);
  914. if (!empty ($formatTemplate) && is_string($formatTemplate)) {
  915. $value= preg_replace(substr($format, 3), $formatTemplate, $value);
  916. }
  917. } elseif (strpos($format, '%') === false) {
  918. $value= date($format, $ts);
  919. } elseif ($ts !== false) {
  920. $value= strftime($format, $ts);
  921. }
  922. } else {
  923. $value= strftime('%Y-%m-%d', $ts);
  924. }
  925. }
  926. break;
  927. case 'array' :
  928. if (is_string($value)) {
  929. $value= unserialize($value);
  930. }
  931. break;
  932. case 'json' :
  933. if (is_string($value) && strlen($value) > 1) {
  934. $value= $this->xpdo->fromJSON($value, true);
  935. }
  936. break;
  937. default :
  938. if (is_string($format) && !empty ($format)) {
  939. if (strpos($format, 're:') === 0) {
  940. if (!empty ($formatTemplate) && is_string($formatTemplate)) {
  941. $value= preg_replace(substr($format, 3), $formatTemplate, $value);
  942. }
  943. } else {
  944. $value= sprintf($format, $value);
  945. }
  946. }
  947. break;
  948. }
  949. }
  950. }
  951. }
  952. return $value;
  953. }
  954. /**
  955. * Gets an object related to this instance by a foreign key relationship.
  956. *
  957. * Use this for 1:? (one:zero-or-one) or 1:1 relationships, which you can
  958. * distinguish by setting the nullability of the field representing the
  959. * foreign key.
  960. *
  961. * For all 1:* relationships for this instance, see {@link getMany()}.
  962. *
  963. * @see xPDOObject::getMany()
  964. * @see xPDOObject::addOne()
  965. * @see xPDOObject::addMany()
  966. *
  967. * @param string $alias Alias of the foreign class representing the related
  968. * object.
  969. * @param object $criteria xPDOCriteria object to get the related objects
  970. * @param boolean|integer $cacheFlag Indicates if the object should be
  971. * cached and optionally, by specifying an integer value, for how many
  972. * seconds.
  973. * @return xPDOObject|null The related object or null if no instance exists.
  974. */
  975. public function & getOne($alias, $criteria= null, $cacheFlag= true) {
  976. $object= null;
  977. if ($fkdef= $this->getFKDefinition($alias)) {
  978. $k= $fkdef['local'];
  979. $fk= $fkdef['foreign'];
  980. if (isset ($this->_relatedObjects[$alias])) {
  981. if (is_object($this->_relatedObjects[$alias])) {
  982. $object= & $this->_relatedObjects[$alias];
  983. return $object;
  984. }
  985. }
  986. if ($criteria === null) {
  987. $criteria= array ($fk => $this->get($k));
  988. }
  989. if ($object= $this->xpdo->getObject($fkdef['class'], $criteria, $cacheFlag)) {
  990. $this->_relatedObjects[$alias]= $object;
  991. }
  992. } else {
  993. $this->xpdo->log(xPDO::LOG_LEVEL_WARN, "Could not getOne: foreign key definition for alias {$alias} not found.");
  994. }
  995. return $object;
  996. }
  997. /**
  998. * Gets a collection of objects related by aggregate or composite relations.
  999. *
  1000. * @see xPDOObject::getOne()
  1001. * @see xPDOObject::addOne()
  1002. * @see xPDOObject::addMany()
  1003. *
  1004. * @param string $alias Alias of the foreign class representing the related
  1005. * object.
  1006. * @param object $criteria xPDOCriteria object to get the related objects
  1007. * @param boolean|integer $cacheFlag Indicates if the objects should be
  1008. * cached and optionally, by specifying an integer value, for how many
  1009. * seconds.
  1010. * @return array A collection of related objects or an empty array.
  1011. */
  1012. public function & getMany($alias, $criteria= null, $cacheFlag= true) {
  1013. $collection= $this->_getRelatedObjectsByFK($alias, $criteria, $cacheFlag);
  1014. return $collection;
  1015. }
  1016. /**
  1017. * Adds an object related to this instance by a foreign key relationship.
  1018. *
  1019. * @see xPDOObject::getOne()
  1020. * @see xPDOObject::getMany()
  1021. * @see xPDOObject::addMany()
  1022. *
  1023. * @param mixed &$obj A single object to be related to this instance.
  1024. * @param string $alias The relation alias of the related object (only
  1025. * required if more than one relation exists to the same foreign class).
  1026. * @return boolean True if the related object was added to this object.
  1027. */
  1028. public function addOne(& $obj, $alias= '') {
  1029. $added= false;
  1030. if (is_object($obj)) {
  1031. if (empty ($alias)) {
  1032. if ($obj->_alias == $obj->_class) {
  1033. $aliases = $this->_getAliases($obj->_class, 1);
  1034. if (!empty($aliases)) {
  1035. $obj->_alias = reset($aliases);
  1036. }
  1037. }
  1038. $alias= $obj->_alias;
  1039. }
  1040. $fkMeta= $this->getFKDefinition($alias);
  1041. if ($fkMeta && $fkMeta['cardinality'] === 'one') {
  1042. $obj->_alias= $alias;
  1043. $fk= $fkMeta['foreign'];
  1044. $key= $fkMeta['local'];
  1045. $owner= isset ($fkMeta['owner']) ? $fkMeta['owner'] : 'local';
  1046. $kval= $this->get($key);
  1047. $fkval= $obj->get($fk);
  1048. if ($owner == 'local') {
  1049. $obj->set($fk, $kval);
  1050. }
  1051. else {
  1052. $this->set($key, $fkval);
  1053. }
  1054. $this->_relatedObjects[$obj->_alias]= $obj;
  1055. $this->setDirty($key);
  1056. $added= true;
  1057. } else {
  1058. $this->xpdo->log(xPDO::LOG_LEVEL_WARN, "Foreign key definition for class {$obj->class}, alias {$obj->_alias} not found, or cardinality is not 'one'.");
  1059. }
  1060. } else {
  1061. $this->xpdo->log(xPDO::LOG_LEVEL_WARN, "Attempt to add a non-object to a relation with alias ({$a…

Large files files are truncated, but you can click here to view the full file