PageRenderTime 53ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/classes/fActiveRecord.php

https://bitbucket.org/wbond/flourish/
PHP | 1951 lines | 1150 code | 317 blank | 484 comment | 287 complexity | e9841459b5b7db2cbe7e7c9b4c5ce025 MD5 | raw file

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

  1. <?php
  2. /**
  3. * An [http://en.wikipedia.org/wiki/Active_record_pattern active record pattern] base class
  4. *
  5. * This class uses fORMSchema to inspect your database and provides an
  6. * OO interface to a single database table. The class dynamically handles
  7. * method calls for getting, setting and other operations on columns. It also
  8. * dynamically handles retrieving and storing related records.
  9. *
  10. * @copyright Copyright (c) 2007-2011 Will Bond, others
  11. * @author Will Bond [wb] <will@flourishlib.com>
  12. * @author Will Bond, iMarc LLC [wb-imarc] <will@imarc.net>
  13. * @license http://flourishlib.com/license
  14. *
  15. * @package Flourish
  16. * @link http://flourishlib.com/fActiveRecord
  17. *
  18. * @version 1.0.0b81
  19. * @changes 1.0.0b81 Fixed a bug with updating a record that contains only an auto-incrementing primary key [wb, 2011-09-06]
  20. * @changes 1.0.0b80 Added support to ::checkCondition() for the `^~` and `$~` operators [wb, 2011-06-20]
  21. * @changes 1.0.0b79 Fixed some bugs in handling relationships between PHP 5.3 namespaced classes [wb, 2011-05-26]
  22. * @changes 1.0.0b78 Backwards Compatibility Break - ::reflect() now returns an associative array instead of a string [wb, 2011-05-10]
  23. * @changes 1.0.0b77 Fixed ::inspect() to not throw an fProgrammerException when a valid element has a `NULL` value [wb, 2011-05-10]
  24. * @changes 1.0.0b76 Added ::clearIdentityMap() [wb, 2011-05-09]
  25. * @changes 1.0.0b75 Fixed a bug where child records of a record with a non-auto-incrementing primary key would not be saved properly for a new record [wb, 2010-12-06]
  26. * @changes 1.0.0b74 Updated ::populate() to use the `binary` type for fRequest::get() [wb, 2010-11-30]
  27. * @changes 1.0.0b73 Backwards Compatibility Break - changed column set methods to treat strings of all whitespace the same as empty string and convert them to `NULL` [wb, 2010-11-29]
  28. * @changes 1.0.0b72 Added the new `comment` element to the reflection signature for `inspect` methods [wb, 2010-11-28]
  29. * @changes 1.0.0b71 Updated class to use fORM::getRelatedClass() [wb, 2010-11-24]
  30. * @changes 1.0.0b70 Added support for PHP 5.3 namespaced fActiveRecord classes [wb, 2010-11-11]
  31. * @changes 1.0.0b69 Backwards Compatibility Break - changed ::validate() to return a nested array of validation messages when there are validation errors on child records [wb-imarc+wb, 2010-10-03]
  32. * @changes 1.0.0b68 Added hooks to ::replicate() [wb, 2010-09-07]
  33. * @changes 1.0.0b67 Updated code to work with the new fORM API [wb, 2010-08-06]
  34. * @changes 1.0.0b66 Fixed a bug with ::store() and non-primary key auto-incrementing columns [wb, 2010-07-05]
  35. * @changes 1.0.0b65 Fixed bugs with ::inspect() making some `min_value` and `max_value` elements available for non-numeric types, fixed ::reflect() to list the `min_value` and `max_value` elements [wb, 2010-06-08]
  36. * @changes 1.0.0b64 BackwardsCompatibilityBreak - changed ::validate()'s returned messages array to have field name keys - added the option to ::validate() to remove field names from messages [wb, 2010-05-26]
  37. * @changes 1.0.0b63 Changed how is_subclass_of() is used to work around a bug in 5.2.x [wb, 2010-04-06]
  38. * @changes 1.0.0b62 Fixed a bug that could cause infinite recursion starting in v1.0.0b60 [wb, 2010-04-02]
  39. * @changes 1.0.0b61 Fixed issues with handling `populate` actions when working with mapped classes [wb, 2010-03-31]
  40. * @changes 1.0.0b60 Fixed issues with handling `associate` and `has` actions when working with mapped classes, added ::validateClass() [wb, 2010-03-30]
  41. * @changes 1.0.0b59 Changed an extended UTF-8 arrow character into the correct `->` [wb, 2010-03-29]
  42. * @changes 1.0.0b58 Fixed ::reflect() to specify the value returned from `set` methods [wb, 2010-03-15]
  43. * @changes 1.0.0b57 Added the `post::loadFromIdentityMap()` hook and fixed ::__construct() to always call the `post::__construct()` hook [wb, 2010-03-14]
  44. * @changes 1.0.0b56 Fixed `$force_cascade` in ::delete() to work even when the restricted relationship is once-removed through an unrestricted relationship [wb, 2010-03-09]
  45. * @changes 1.0.0b55 Fixed ::load() to that related records are cleared, requiring them to be loaded from the database [wb, 2010-03-04]
  46. * @changes 1.0.0b54 Fixed detection of route name for one-to-one relationships in ::delete() [wb, 2010-03-03]
  47. * @changes 1.0.0b53 Fixed a bug where related records with a primary key that contained a foreign key with an on update cascade clause would be deleted when changing the value of the column referenced by the foreign key [wb, 2009-12-17]
  48. * @changes 1.0.0b52 Backwards Compatibility Break - Added the $force_cascade parameter to ::delete() and ::store() - enabled calling ::prepare() and ::encode() for non-column get methods, added `::has{RelatedRecords}()` methods [wb, 2009-12-16]
  49. * @changes 1.0.0b51 Made ::changed() properly recognize that a blank string and NULL are equivalent due to the way that ::set() casts values [wb, 2009-11-14]
  50. * @changes 1.0.0b50 Fixed a bug with trying to load by a multi-column primary key where one of the columns was not specified [wb, 2009-11-13]
  51. * @changes 1.0.0b49 Fixed a bug affecting where conditions with columns that are not null but have a default value [wb, 2009-11-03]
  52. * @changes 1.0.0b48 Updated code for the new fORMDatabase and fORMSchema APIs [wb, 2009-10-28]
  53. * @changes 1.0.0b47 Changed `::associate{RelatedRecords}()`, `::link{RelatedRecords}()` and `::populate{RelatedRecords}()` to allow for method chaining [wb, 2009-10-22]
  54. * @changes 1.0.0b46 Changed SQL statements to use value placeholders and identifier escaping [wb, 2009-10-22]
  55. * @changes 1.0.0b45 Added support for `!~`, `&~`, `><` and OR comparisons to ::checkConditions(), made object handling in ::checkConditions() more robust [wb, 2009-09-21]
  56. * @changes 1.0.0b44 Updated code for new fValidationException API [wb, 2009-09-18]
  57. * @changes 1.0.0b43 Updated code for new fRecordSet API [wb, 2009-09-16]
  58. * @changes 1.0.0b42 Corrected a grammar bug in ::hash() [wb, 2009-09-09]
  59. * @changes 1.0.0b41 Fixed a bug in the last version that would cause issues with classes containing a custom class to table mapping [wb, 2009-09-01]
  60. * @changes 1.0.0b40 Added a check to the configuration part of ::__construct() to ensure modelled tables have primary keys [wb, 2009-08-26]
  61. * @changes 1.0.0b39 Changed `set{ColumnName}()` methods to return the record for method chaining, fixed a bug with loading by multi-column unique constraints, fixed a bug with ::load() [wb, 2009-08-26]
  62. * @changes 1.0.0b38 Updated ::changed() to do a strict comparison when at least one value is NULL [wb, 2009-08-17]
  63. * @changes 1.0.0b37 Changed ::__construct() to allow any Iterator object instead of just fResult [wb, 2009-08-12]
  64. * @changes 1.0.0b36 Fixed a bug with setting NULL values from v1.0.0b33 [wb, 2009-08-10]
  65. * @changes 1.0.0b35 Fixed a bug with unescaping data in ::loadFromResult() from v1.0.0b33 [wb, 2009-08-10]
  66. * @changes 1.0.0b34 Added the ability to compare fActiveRecord objects in ::checkConditions() [wb, 2009-08-07]
  67. * @changes 1.0.0b33 Performance enhancements to ::__call() and ::__construct() [wb, 2009-08-07]
  68. * @changes 1.0.0b32 Changed ::delete() to remove auto-incrementing primary keys after the post::delete() hook [wb, 2009-07-29]
  69. * @changes 1.0.0b31 Fixed a bug with loading a record by a multi-column primary key, fixed one-to-one relationship API [wb, 2009-07-21]
  70. * @changes 1.0.0b30 Updated ::reflect() for new fORM::callReflectCallbacks() API [wb, 2009-07-13]
  71. * @changes 1.0.0b29 Updated to use new fORM::callInspectCallbacks() method [wb, 2009-07-13]
  72. * @changes 1.0.0b28 Fixed a bug where records would break the identity map at the end of ::store() [wb, 2009-07-09]
  73. * @changes 1.0.0b27 Changed ::hash() from a protected method to a static public/internal method that requires the class name for non-fActiveRecord values [wb, 2009-07-09]
  74. * @changes 1.0.0b26 Added ::checkConditions() from fRecordSet [wb, 2009-07-08]
  75. * @changes 1.0.0b25 Updated ::validate() to use new fORMValidation API, including new message search/replace functionality [wb, 2009-07-01]
  76. * @changes 1.0.0b24 Changed ::validate() to remove duplicate validation messages [wb, 2009-06-30]
  77. * @changes 1.0.0b23 Updated code for new fORMValidation::validateRelated() API [wb, 2009-06-26]
  78. * @changes 1.0.0b22 Added support for the $formatting parameter to encode methods on char, text and varchar columns [wb, 2009-06-19]
  79. * @changes 1.0.0b21 Performance tweaks and updates for fORM and fORMRelated API changes [wb, 2009-06-15]
  80. * @changes 1.0.0b20 Changed replacement values in preg_replace() calls to be properly escaped [wb, 2009-06-11]
  81. * @changes 1.0.0b19 Added `list{RelatedRecords}()` methods, updated code for new fORMRelated API [wb, 2009-06-02]
  82. * @changes 1.0.0b18 Changed ::store() to use new fORMRelated::store() method [wb, 2009-06-02]
  83. * @changes 1.0.0b17 Added some missing parameter information to ::reflect() [wb, 2009-06-01]
  84. * @changes 1.0.0b16 Fixed bugs in ::__clone() and ::replicate() related to recursive relationships [wb-imarc, 2009-05-20]
  85. * @changes 1.0.0b15 Fixed an incorrect variable reference in ::store() [wb, 2009-05-06]
  86. * @changes 1.0.0b14 ::store() no longer tries to get an auto-incrementing ID from the database if a value was set [wb, 2009-05-02]
  87. * @changes 1.0.0b13 ::delete(), ::load(), ::populate() and ::store() now return the record to allow for method chaining [wb, 2009-03-23]
  88. * @changes 1.0.0b12 ::set() now removes commas from integers and floats to prevent validation issues [wb, 2009-03-22]
  89. * @changes 1.0.0b11 ::encode() no longer adds commas to floats [wb, 2009-03-22]
  90. * @changes 1.0.0b10 ::__wakeup() no longer registers the record as the definitive copy in the identity map [wb, 2009-03-22]
  91. * @changes 1.0.0b9 Changed ::__construct() to populate database default values when a non-existing record is instantiated [wb, 2009-01-12]
  92. * @changes 1.0.0b8 Fixed ::exists() to properly detect cases when an existing record has one or more NULL values in the primary key [wb, 2009-01-11]
  93. * @changes 1.0.0b7 Fixed ::__construct() to not trigger the post::__construct() hook when force-configured [wb, 2008-12-30]
  94. * @changes 1.0.0b6 ::__construct() now accepts an associative array matching any unique key or primary key, fixed the post::__construct() hook to be called once for each record [wb, 2008-12-26]
  95. * @changes 1.0.0b5 Fixed ::replicate() to use plural record names for related records [wb, 2008-12-12]
  96. * @changes 1.0.0b4 Added ::replicate() to allow cloning along with related records [wb, 2008-12-12]
  97. * @changes 1.0.0b3 Changed ::__clone() to clone objects contains in the values and cache arrays [wb, 2008-12-11]
  98. * @changes 1.0.0b2 Added the ::__clone() method to properly duplicate a record [wb, 2008-12-04]
  99. * @changes 1.0.0b The initial implementation [wb, 2007-08-04]
  100. */
  101. abstract class fActiveRecord
  102. {
  103. // The following constants allow for nice looking callbacks to static methods
  104. const assign = 'fActiveRecord::assign';
  105. const changed = 'fActiveRecord::changed';
  106. const checkConditions = 'fActiveRecord::checkConditions';
  107. const forceConfigure = 'fActiveRecord::forceConfigure';
  108. const hasOld = 'fActiveRecord::hasOld';
  109. const reset = 'fActiveRecord::reset';
  110. const retrieveOld = 'fActiveRecord::retrieveOld';
  111. const validateClass = 'fActiveRecord::validateClass';
  112. /**
  113. * Caches callbacks for methods
  114. *
  115. * @var array
  116. */
  117. static protected $callback_cache = array();
  118. /**
  119. * An array of flags indicating a class has been configured
  120. *
  121. * @var array
  122. */
  123. static protected $configured = array();
  124. /**
  125. * Maps objects via their primary key
  126. *
  127. * @var array
  128. */
  129. static protected $identity_map = array();
  130. /**
  131. * Caches method name parsings
  132. *
  133. * @var array
  134. */
  135. static protected $method_name_cache = array();
  136. /**
  137. * Keeps track of the recursive call level of replication so we can clear the map
  138. *
  139. * @var integer
  140. */
  141. static protected $replicate_level = 0;
  142. /**
  143. * Keeps a list of records that have been replicated
  144. *
  145. * @var array
  146. */
  147. static protected $replicate_map = array();
  148. /**
  149. * Contains a list of what columns in each class need to be unescaped and what data type they are
  150. *
  151. * @var array
  152. */
  153. static protected $unescape_map = array();
  154. /**
  155. * Sets a value to the `$values` array, preserving the old value in `$old_values`
  156. *
  157. * @internal
  158. *
  159. * @param array &$values The current values
  160. * @param array &$old_values The old values
  161. * @param string $column The column to set
  162. * @param mixed $value The value to set
  163. * @return void
  164. */
  165. static public function assign(&$values, &$old_values, $column, $value)
  166. {
  167. if (!isset($old_values[$column])) {
  168. $old_values[$column] = array();
  169. }
  170. $old_values[$column][] = $values[$column];
  171. $values[$column] = $value;
  172. }
  173. /**
  174. * Checks to see if a value has changed
  175. *
  176. * @internal
  177. *
  178. * @param array &$values The current values
  179. * @param array &$old_values The old values
  180. * @param string $column The column to check
  181. * @return boolean If the value for the column specified has changed
  182. */
  183. static public function changed(&$values, &$old_values, $column)
  184. {
  185. if (!isset($old_values[$column])) {
  186. return FALSE;
  187. }
  188. $oldest_value = $old_values[$column][0];
  189. $new_value = $values[$column];
  190. // We do a strict comparison when one of the values is NULL since
  191. // NULL is almost always meant to be distinct from 0, FALSE, etc.
  192. // However, since we cast blank strings to NULL in ::set() but a blank
  193. // string could come out of the database, we consider them to be
  194. // equivalent, so we don't do a strict comparison
  195. if (($oldest_value === NULL && $new_value !== '') || ($new_value === NULL && $oldest_value !== '')) {
  196. return $oldest_value !== $new_value;
  197. }
  198. return $oldest_value != $new_value;
  199. }
  200. /**
  201. * Ensures a class extends fActiveRecord
  202. *
  203. * @internal
  204. *
  205. * @param string $class The class to check
  206. * @return boolean If the class is an fActiveRecord descendant
  207. */
  208. static public function checkClass($class)
  209. {
  210. if (isset(self::$configured[$class])) {
  211. return TRUE;
  212. }
  213. if (!is_string($class) || !$class || !class_exists($class) || !($class == 'fActiveRecord' || is_subclass_of($class, 'fActiveRecord'))) {
  214. return FALSE;
  215. }
  216. return TRUE;
  217. }
  218. /**
  219. * Checks to see if a record matches a condition
  220. *
  221. * @internal
  222. *
  223. * @param string $operator The record to check
  224. * @param mixed $value The value to compare to
  225. * @param mixed $result The result of the method call(s)
  226. * @return boolean If the comparison was successful
  227. */
  228. static private function checkCondition($operator, $value, $result)
  229. {
  230. $was_array = is_array($value);
  231. if (!$was_array) { $value = array($value); }
  232. foreach ($value as $i => $_value) {
  233. if (is_object($_value)) {
  234. if ($_value instanceof fActiveRecord) {
  235. continue;
  236. }
  237. if (method_exists($_value, '__toString')) {
  238. $value[$i] = $_value->__toString();
  239. }
  240. }
  241. }
  242. if (!$was_array) { $value = $value[0]; }
  243. $was_array = is_array($result);
  244. if (!$was_array) { $result = array($result); }
  245. foreach ($result as $i => $_result) {
  246. if (is_object($_result)) {
  247. if ($_result instanceof fActiveRecord) {
  248. continue;
  249. }
  250. if (method_exists($_result, '__toString')) {
  251. $result[$i] = $_result->__toString();
  252. }
  253. }
  254. }
  255. if (!$was_array) { $result = $result[0]; }
  256. if ($operator == '~' && !is_array($value) && is_array($result)) {
  257. $value = fORMDatabase::parseSearchTerms($value, TRUE);
  258. }
  259. if (in_array($operator, array('~', '&~', '!~', '^~', '$~'))) {
  260. settype($value, 'array');
  261. settype($result, 'array');
  262. }
  263. switch ($operator) {
  264. case '&~':
  265. foreach ($value as $_value) {
  266. if (fUTF8::ipos($result[0], $_value) === FALSE) {
  267. return FALSE;
  268. }
  269. }
  270. break;
  271. case '~':
  272. // Handles fuzzy search on multiple method calls
  273. if (count($result) > 1) {
  274. foreach ($value as $_value) {
  275. $found = FALSE;
  276. foreach ($result as $_result) {
  277. if (fUTF8::ipos($_result, $_value) !== FALSE) {
  278. $found = TRUE;
  279. }
  280. }
  281. if (!$found) {
  282. return FALSE;
  283. }
  284. }
  285. break;
  286. }
  287. // No break exists since a ~ on a single method call acts
  288. // similar to the other LIKE operators
  289. case '!~':
  290. case '^~':
  291. case '$~':
  292. if ($operator == '$~') {
  293. $result_len = fUTF8::len($result[0]);
  294. }
  295. foreach ($value as $_value) {
  296. $pos = fUTF8::ipos($result[0], $_value);
  297. if ($operator == '^~' && $pos === 0) {
  298. return TRUE;
  299. } elseif ($operator == '$~' && $pos === $result_len - fUTF8::len($_value)) {
  300. return TRUE;
  301. } elseif ($pos !== FALSE) {
  302. return $operator != '!~';
  303. }
  304. }
  305. if ($operator != '!~') {
  306. return FALSE;
  307. }
  308. break;
  309. case '=':
  310. if ($value instanceof fActiveRecord && $result instanceof fActiveRecord) {
  311. if (get_class($value) != get_class($result) || !$value->exists() || !$result->exists() || self::hash($value) != self::hash($result)) {
  312. return FALSE;
  313. }
  314. } elseif (is_array($value) && !in_array($result, $value)) {
  315. return FALSE;
  316. } elseif (!is_array($value) && $result != $value) {
  317. return FALSE;
  318. }
  319. break;
  320. case '!':
  321. if ($value instanceof fActiveRecord && $result instanceof fActiveRecord) {
  322. if (get_class($value) == get_class($result) && $value->exists() && $result->exists() && self::hash($value) == self::hash($result)) {
  323. return FALSE;
  324. }
  325. } elseif (is_array($value) && in_array($result, $value)) {
  326. return FALSE;
  327. } elseif (!is_array($value) && $result == $value) {
  328. return FALSE;
  329. }
  330. break;
  331. case '<':
  332. if ($result >= $value) {
  333. return FALSE;
  334. }
  335. break;
  336. case '<=':
  337. if ($result > $value) {
  338. return FALSE;
  339. }
  340. break;
  341. case '>':
  342. if ($result <= $value) {
  343. return FALSE;
  344. }
  345. break;
  346. case '>=':
  347. if ($result < $value) {
  348. return FALSE;
  349. }
  350. break;
  351. }
  352. return TRUE;
  353. }
  354. /**
  355. * Checks to see if a record matches all of the conditions
  356. *
  357. * @internal
  358. *
  359. * @param fActiveRecord $record The record to check
  360. * @param array $conditions The conditions to check - see fRecordSet::filter() for format details
  361. * @return boolean If the record meets all conditions
  362. */
  363. static public function checkConditions($record, $conditions)
  364. {
  365. foreach ($conditions as $method => $value) {
  366. // Split the operator off of the end of the method name
  367. if (in_array(substr($method, -2), array('<=', '>=', '!=', '<>', '!~', '&~', '^~', '$~', '><'))) {
  368. $operator = strtr(
  369. substr($method, -2),
  370. array(
  371. '<>' => '!',
  372. '!=' => '!'
  373. )
  374. );
  375. $method = substr($method, 0, -2);
  376. } else {
  377. $operator = substr($method, -1);
  378. $method = substr($method, 0, -1);
  379. }
  380. if (preg_match('#(?<!\|)\|(?!\|)#', $method)) {
  381. $methods = explode('|', $method);
  382. $values = $value;
  383. $operators = array();
  384. foreach ($methods as &$_method) {
  385. if (in_array(substr($_method, -2), array('<=', '>=', '!=', '<>', '!~', '&~', '^~', '$~', '><'))) {
  386. $operators[] = strtr(
  387. substr($_method, -2),
  388. array(
  389. '<>' => '!',
  390. '!=' => '!'
  391. )
  392. );
  393. $_method = substr($_method, 0, -2);
  394. } elseif (!ctype_alnum(substr($_method, -1))) {
  395. $operators[] = substr($_method, -1);
  396. $_method = substr($_method, 0, -1);
  397. }
  398. }
  399. $operators[] = $operator;
  400. if (sizeof($operators) == 1) {
  401. // Handle fuzzy searches
  402. if ($operator == '~') {
  403. $results = array();
  404. foreach ($methods as $method) {
  405. $results[] = $record->$method();
  406. }
  407. if (!self::checkCondition($operator, $value, $results)) {
  408. return FALSE;
  409. }
  410. // Handle intersection
  411. } elseif ($operator == '><') {
  412. if (sizeof($methods) != 2 || sizeof($values) != 2) {
  413. throw new fProgrammerException(
  414. 'The intersection operator, %s, requires exactly two methods and two values',
  415. $operator
  416. );
  417. }
  418. $results = array();
  419. $results[0] = $record->{$methods[0]}();
  420. $results[1] = $record->{$methods[1]}();
  421. if ($results[1] === NULL && $values[1] === NULL) {
  422. if (!self::checkCondition('=', $values[0], $results[0])) {
  423. return FALSE;
  424. }
  425. } else {
  426. $starts_between_values = FALSE;
  427. $overlaps_value_1 = FALSE;
  428. if ($values[1] !== NULL) {
  429. $start_lt_value_1 = self::checkCondition('<', $values[0], $results[0]);
  430. $start_gt_value_2 = self::checkCondition('>', $values[1], $results[0]);
  431. $starts_between_values = !$start_lt_value_1 && !$start_gt_value_2;
  432. }
  433. if ($results[1] !== NULL) {
  434. $start_gt_value_1 = self::checkCondition('>', $values[0], $results[0]);
  435. $end_lt_value_1 = self::checkCondition('<', $values[0], $results[1]);
  436. $overlaps_value_1 = !$start_gt_value_1 && !$end_lt_value_1;
  437. }
  438. if (!$starts_between_values && !$overlaps_value_1) {
  439. return FALSE;
  440. }
  441. }
  442. } else {
  443. throw new fProgrammerException(
  444. 'An invalid comparison operator, %s, was specified for multiple columns',
  445. $operator
  446. );
  447. }
  448. // Handle OR conditions
  449. } else {
  450. if (sizeof($methods) != sizeof($values)) {
  451. throw new fProgrammerException(
  452. 'When performing an %1$s comparison there must be an equal number of methods and values, however there are not',
  453. 'OR',
  454. sizeof($methods),
  455. sizeof($values)
  456. );
  457. }
  458. if (sizeof($methods) != sizeof($operators)) {
  459. throw new fProgrammerException(
  460. 'When performing an %s comparison there must be a comparison operator for each column, however one or more is missing',
  461. 'OR'
  462. );
  463. }
  464. $results = array();
  465. $iterations = sizeof($methods);
  466. for ($i=0; $i<$iterations; $i++) {
  467. $results[] = self::checkCondition($operators[$i], $values[$i], $record->{$methods[$i]}());
  468. }
  469. if (!array_filter($results)) {
  470. return FALSE;
  471. }
  472. }
  473. // Single method comparisons
  474. } else {
  475. $result = $record->$method();
  476. if (!self::checkCondition($operator, $value, $result)) {
  477. return FALSE;
  478. }
  479. }
  480. }
  481. return TRUE;
  482. }
  483. /**
  484. * Clears the identity map
  485. *
  486. * @return void
  487. */
  488. static public function clearIdentityMap()
  489. {
  490. self::$identity_map = array();
  491. }
  492. /**
  493. * Composes text using fText if loaded
  494. *
  495. * @param string $message The message to compose
  496. * @param mixed $component A string or number to insert into the message
  497. * @param mixed ...
  498. * @return string The composed and possible translated message
  499. */
  500. static protected function compose($message)
  501. {
  502. $args = array_slice(func_get_args(), 1);
  503. if (class_exists('fText', FALSE)) {
  504. return call_user_func_array(
  505. array('fText', 'compose'),
  506. array($message, $args)
  507. );
  508. } else {
  509. return vsprintf($message, $args);
  510. }
  511. }
  512. /**
  513. * Takes information from a method call and determines the subject, route and if subject was plural
  514. *
  515. * @param string $class The class the method was called on
  516. * @param string $subject An underscore_notation subject - either a singular or plural class name
  517. * @param string $route The route to the subject
  518. * @return array An array with the structure: array(0 => $subject, 1 => $route, 2 => $plural)
  519. */
  520. static private function determineSubject($class, $subject, $route)
  521. {
  522. $schema = fORMSchema::retrieve($class);
  523. $table = fORM::tablize($class);
  524. $type = '*-to-many';
  525. $plural = FALSE;
  526. // one-to-many relationships need to use plural forms
  527. $singular_form = fGrammar::singularize($subject, TRUE);
  528. if ($singular_form && fORM::isClassMappedToTable($singular_form)) {
  529. $subject = $singular_form;
  530. $plural = TRUE;
  531. } elseif (!fORM::isClassMappedToTable($subject) && in_array(fGrammar::underscorize($subject), $schema->getTables())) {
  532. $subject = fGrammar::singularize($subject);
  533. $plural = TRUE;
  534. }
  535. $related_table = fORM::tablize($subject);
  536. $one_to_one = fORMSchema::isOneToOne($schema, $table, $related_table, $route);
  537. if ($one_to_one) {
  538. $type = 'one-to-one';
  539. }
  540. if (($one_to_one && $plural) || (!$plural && !$one_to_one)) {
  541. throw new fProgrammerException(
  542. 'The table %1$s is not in a %2$srelationship with the table %3$s',
  543. $table,
  544. $type,
  545. $related_table
  546. );
  547. }
  548. $route = fORMSchema::getRouteName($schema, $table, $related_table, $route, $type);
  549. return array($subject, $route, $plural);
  550. }
  551. /**
  552. * Ensures that ::configure() has been called for the class
  553. *
  554. * @internal
  555. *
  556. * @param string $class The class to configure
  557. * @return void
  558. */
  559. static public function forceConfigure($class)
  560. {
  561. if (isset(self::$configured[$class])) {
  562. return;
  563. }
  564. new $class();
  565. }
  566. /**
  567. * Takes a row of data or a primary key and makes a hash from the primary key
  568. *
  569. * @internal
  570. *
  571. * @param fActiveRecord|array|string|int $record An fActiveRecord object, an array of the records data, an array of primary key data or a scalar primary key value
  572. * @param string $class The class name, if $record isn't an fActiveRecord
  573. * @return string|NULL A hash of the record's primary key value or NULL if the record doesn't exist yet
  574. */
  575. static public function hash($record, $class=NULL)
  576. {
  577. if ($record instanceof fActiveRecord && !$record->exists()) {
  578. return NULL;
  579. }
  580. if ($class === NULL) {
  581. if (!$record instanceof fActiveRecord) {
  582. throw new fProgrammerException(
  583. 'The class of the record must be provided if the record specified is not an instance of fActiveRecord'
  584. );
  585. }
  586. $class = get_class($record);
  587. }
  588. $schema = fORMSchema::retrieve($class);
  589. $table = fORM::tablize($class);
  590. $pk_columns = $schema->getKeys($table, 'primary');
  591. // Build an array of just the primary key data
  592. $pk_data = array();
  593. foreach ($pk_columns as $pk_column) {
  594. if ($record instanceof fActiveRecord) {
  595. $value = (self::hasOld($record->old_values, $pk_column)) ? self::retrieveOld($record->old_values, $pk_column) : $record->values[$pk_column];
  596. } elseif (is_array($record)) {
  597. $value = $record[$pk_column];
  598. } else {
  599. $value = $record;
  600. }
  601. $pk_data[$pk_column] = fORM::scalarize(
  602. $class,
  603. $pk_column,
  604. $value
  605. );
  606. if (is_numeric($pk_data[$pk_column]) || is_object($pk_data[$pk_column])) {
  607. $pk_data[$pk_column] = (string) $pk_data[$pk_column];
  608. }
  609. }
  610. return md5(serialize($pk_data));
  611. }
  612. /**
  613. * Checks to see if an old value exists for a column
  614. *
  615. * @internal
  616. *
  617. * @param array &$old_values The old values
  618. * @param string $column The column to set
  619. * @return boolean If an old value for that column exists
  620. */
  621. static public function hasOld(&$old_values, $column)
  622. {
  623. return array_key_exists($column, $old_values);
  624. }
  625. /**
  626. * Resets the configuration of the class
  627. *
  628. * @internal
  629. *
  630. * @return void
  631. */
  632. static public function reset()
  633. {
  634. self::$callback_cache = array();
  635. self::$configured = array();
  636. self::$identity_map = array();
  637. self::$method_name_cache = array();
  638. self::$unescape_map = array();
  639. }
  640. /**
  641. * Retrieves the oldest value for a column or all old values
  642. *
  643. * @internal
  644. *
  645. * @param array &$old_values The old values
  646. * @param string $column The column to get
  647. * @param mixed $default The default value to return if no value exists
  648. * @param boolean $return_all Return the array of all old values for this column instead of just the oldest
  649. * @return mixed The old value for the column
  650. */
  651. static public function retrieveOld(&$old_values, $column, $default=NULL, $return_all=FALSE)
  652. {
  653. if (!isset($old_values[$column])) {
  654. return $default;
  655. }
  656. if ($return_all === TRUE) {
  657. return $old_values[$column];
  658. }
  659. return $old_values[$column][0];
  660. }
  661. /**
  662. * Ensures a class extends fActiveRecord
  663. *
  664. * @internal
  665. *
  666. * @param string $class The class to verify
  667. * @return void
  668. */
  669. static public function validateClass($class)
  670. {
  671. if (isset(self::$configured[$class])) {
  672. return TRUE;
  673. }
  674. if (!self::checkClass($class)) {
  675. throw new fProgrammerException(
  676. 'The class specified, %1$s, does not appear to be a valid %2$s class',
  677. $class,
  678. 'fActiveRecord'
  679. );
  680. }
  681. }
  682. /**
  683. * A data store for caching data related to a record, the structure of this is completely up to the developer using it
  684. *
  685. * @var array
  686. */
  687. protected $cache = array();
  688. /**
  689. * The old values for this record
  690. *
  691. * Column names are the keys, but a column key will only be present if a
  692. * value has changed. The value associated with each key is an array of
  693. * old values with the first entry being the oldest value. The static
  694. * methods ::assign(), ::changed(), ::hasOld() and ::retrieveOld() are the
  695. * best way to interact with this array.
  696. *
  697. * @var array
  698. */
  699. protected $old_values = array();
  700. /**
  701. * Records that are related to the current record via some relationship
  702. *
  703. * This array is used to cache related records so that a database query
  704. * is not required each time related records are accessed. The fORMRelated
  705. * class handles most of the interaction with this array.
  706. *
  707. * @var array
  708. */
  709. protected $related_records = array();
  710. /**
  711. * The values for this record
  712. *
  713. * This array always contains every column in the database table as a key
  714. * with the value being the current value.
  715. *
  716. * @var array
  717. */
  718. protected $values = array();
  719. /**
  720. * Handles all method calls for columns, related records and hook callbacks
  721. *
  722. * Dynamically handles `get`, `set`, `prepare`, `encode` and `inspect`
  723. * methods for each column in this record. Method names are in the form
  724. * `verbColumName()`.
  725. *
  726. * This method also handles `associate`, `build`, `count`, `has`, and `link`
  727. * verbs for records in many-to-many relationships; `build`, `count`, `has`
  728. * and `populate` verbs for all related records in one-to-many relationships
  729. * and `create`, `has` and `populate` verbs for all related records in
  730. * one-to-one relationships, and the `create` verb for all related records
  731. * in many-to-one relationships.
  732. *
  733. * Method callbacks registered through fORM::registerActiveRecordMethod()
  734. * will be delegated via this method.
  735. *
  736. * @param string $method_name The name of the method called
  737. * @param array $parameters The parameters passed
  738. * @return mixed The value returned by the method called
  739. */
  740. public function __call($method_name, $parameters)
  741. {
  742. $class = get_class($this);
  743. if (!isset(self::$callback_cache[$class][$method_name])) {
  744. if (!isset(self::$callback_cache[$class])) {
  745. self::$callback_cache[$class] = array();
  746. }
  747. $callback = fORM::getActiveRecordMethod($class, $method_name);
  748. self::$callback_cache[$class][$method_name] = $callback ? $callback : FALSE;
  749. }
  750. if ($callback = self::$callback_cache[$class][$method_name]) {
  751. return call_user_func_array(
  752. $callback,
  753. array(
  754. $this,
  755. &$this->values,
  756. &$this->old_values,
  757. &$this->related_records,
  758. &$this->cache,
  759. $method_name,
  760. $parameters
  761. )
  762. );
  763. }
  764. if (!isset(self::$method_name_cache[$method_name])) {
  765. list ($action, $subject) = fORM::parseMethod($method_name);
  766. if (in_array($action, array('get', 'encode', 'prepare', 'inspect', 'set'))) {
  767. $subject = fGrammar::underscorize($subject);
  768. } else {
  769. if (in_array($action, array('build', 'count', 'inject', 'link', 'list', 'tally'))) {
  770. $subject = fGrammar::singularize($subject);
  771. }
  772. $subject = fORM::getRelatedClass($class, $subject);
  773. }
  774. self::$method_name_cache[$method_name] = array(
  775. 'action' => $action,
  776. 'subject' => $subject
  777. );
  778. } else {
  779. $action = self::$method_name_cache[$method_name]['action'];
  780. $subject = self::$method_name_cache[$method_name]['subject'];
  781. }
  782. switch ($action) {
  783. // Value methods
  784. case 'get':
  785. return $this->get($subject);
  786. case 'encode':
  787. if (isset($parameters[0])) {
  788. return $this->encode($subject, $parameters[0]);
  789. }
  790. return $this->encode($subject);
  791. case 'prepare':
  792. if (isset($parameters[0])) {
  793. return $this->prepare($subject, $parameters[0]);
  794. }
  795. return $this->prepare($subject);
  796. case 'inspect':
  797. if (isset($parameters[0])) {
  798. return $this->inspect($subject, $parameters[0]);
  799. }
  800. return $this->inspect($subject);
  801. case 'set':
  802. if (sizeof($parameters) < 1) {
  803. throw new fProgrammerException(
  804. 'The method, %s(), requires at least one parameter',
  805. $method_name
  806. );
  807. }
  808. return $this->set($subject, $parameters[0]);
  809. // Related data methods
  810. case 'associate':
  811. if (sizeof($parameters) < 1) {
  812. throw new fProgrammerException(
  813. 'The method, %s(), requires at least one parameter',
  814. $method_name
  815. );
  816. }
  817. $records = $parameters[0];
  818. $route = isset($parameters[1]) ? $parameters[1] : NULL;
  819. list ($subject, $route, $plural) = self::determineSubject($class, $subject, $route);
  820. if ($plural) {
  821. fORMRelated::associateRecords($class, $this->related_records, $subject, $records, $route);
  822. } else {
  823. fORMRelated::associateRecord($class, $this->related_records, $subject, $records, $route);
  824. }
  825. return $this;
  826. case 'build':
  827. if (isset($parameters[0])) {
  828. return fORMRelated::buildRecords($class, $this->values, $this->related_records, $subject, $parameters[0]);
  829. }
  830. return fORMRelated::buildRecords($class, $this->values, $this->related_records, $subject);
  831. case 'count':
  832. if (isset($parameters[0])) {
  833. return fORMRelated::countRecords($class, $this->values, $this->related_records, $subject, $parameters[0]);
  834. }
  835. return fORMRelated::countRecords($class, $this->values, $this->related_records, $subject);
  836. case 'create':
  837. if (isset($parameters[0])) {
  838. return fORMRelated::createRecord($class, $this->values, $this->related_records, $subject, $parameters[0]);
  839. }
  840. return fORMRelated::createRecord($class, $this->values, $this->related_records, $subject);
  841. case 'has':
  842. $route = isset($parameters[0]) ? $parameters[0] : NULL;
  843. list ($subject, $route, ) = self::determineSubject($class, $subject, $route);
  844. return fORMRelated::hasRecords($class, $this->values, $this->related_records, $subject, $route);
  845. case 'inject':
  846. if (sizeof($parameters) < 1) {
  847. throw new fProgrammerException(
  848. 'The method, %s(), requires at least one parameter',
  849. $method_name
  850. );
  851. }
  852. if (isset($parameters[1])) {
  853. return fORMRelated::setRecordSet($class, $this->related_records, $subject, $parameters[0], $parameters[1]);
  854. }
  855. return fORMRelated::setRecordSet($class, $this->related_records, $subject, $parameters[0]);
  856. case 'link':
  857. if (isset($parameters[0])) {
  858. fORMRelated::linkRecords($class, $this->related_records, $subject, $parameters[0]);
  859. } else {
  860. fORMRelated::linkRecords($class, $this->related_records, $subject);
  861. }
  862. return $this;
  863. case 'list':
  864. if (isset($parameters[0])) {
  865. return fORMRelated::getPrimaryKeys($class, $this->values, $this->related_records, $subject, $parameters[0]);
  866. }
  867. return fORMRelated::getPrimaryKeys($class, $this->values, $this->related_records, $subject);
  868. case 'populate':
  869. $route = isset($parameters[0]) ? $parameters[0] : NULL;
  870. list ($subject, $route, ) = self::determineSubject($class, $subject, $route);
  871. fORMRelated::populateRecords($class, $this->related_records, $subject, $route);
  872. return $this;
  873. case 'tally':
  874. if (sizeof($parameters) < 1) {
  875. throw new fProgrammerException(
  876. 'The method, %s(), requires at least one parameter',
  877. $method_name
  878. );
  879. }
  880. if (isset($parameters[1])) {
  881. return fORMRelated::setCount($class, $this->related_records, $subject, $parameters[0], $parameters[1]);
  882. }
  883. return fORMRelated::setCount($class, $this->related_records, $subject, $parameters[0]);
  884. // Error handler
  885. default:
  886. throw new fProgrammerException(
  887. 'Unknown method, %s(), called',
  888. $method_name
  889. );
  890. }
  891. }
  892. /**
  893. * Creates a clone of a record
  894. *
  895. * If the record has an auto incrementing primary key, the primary key will
  896. * be erased in the clone. If the primary key is not auto incrementing,
  897. * the primary key will be left as-is in the clone. In either situation the
  898. * clone will return `FALSE` from the ::exists() method until ::store() is
  899. * called.
  900. *
  901. * @internal
  902. *
  903. * @return fActiveRecord
  904. */
  905. public function __clone()
  906. {
  907. $class = get_class($this);
  908. // Copy values and cache, making sure objects are cloned to prevent reference issues
  909. $temp_values = $this->values;
  910. $new_values = array();
  911. $this->values =& $new_values;
  912. foreach ($temp_values as $column => $value) {
  913. $this->values[$column] = fORM::replicate($class, $column, $value);
  914. }
  915. $temp_cache = $this->cache;
  916. $new_cache = array();
  917. $this->cache =& $new_cache;
  918. foreach ($temp_cache as $key => $value) {
  919. if (is_object($value)) {
  920. $this->cache[$key] = clone $value;
  921. } else {
  922. $this->cache[$key] = $value;
  923. }
  924. }
  925. // Related records are purged
  926. $new_related_records = array();
  927. $this->related_records =& $new_related_records;
  928. // Old values are changed to look like the record is non-existant
  929. $new_old_values = array();
  930. $this->old_values =& $new_old_values;
  931. foreach (array_keys($this->values) as $key) {
  932. $this->old_values[$key] = array(NULL);
  933. }
  934. // If we have a single auto incrementing primary key, remove the value
  935. $schema = fORMSchema::retrieve($class);
  936. $table = fORM::tablize($class);
  937. $pk_columns = $schema->getKeys($table, 'primary');
  938. if (sizeof($pk_columns) == 1 && $schema->getColumnInfo($table, $pk_columns[0], 'auto_increment')) {
  939. $this->values[$pk_columns[0]] = NULL;
  940. unset($this->old_values[$pk_columns[0]]);
  941. }
  942. }
  943. /**
  944. * Creates a new record or loads one from the database - if a primary key or unique key is provided the record will be loaded
  945. *
  946. * @throws fNotFoundException When the record specified by `$key` can not be found in the database
  947. *
  948. * @param mixed $key The primary key or unique key value(s) - single column primary keys will accept a scalar value, all others must be an associative array of `(string) {column} => (mixed) {value}`
  949. * @return fActiveRecord
  950. */
  951. public function __construct($key=NULL)
  952. {
  953. $class = get_class($this);
  954. $schema = fORMSchema::retrieve($class);
  955. // If the features of this class haven't been set yet, do it
  956. if (!isset(self::$configured[$class])) {
  957. self::$configured[$class] = TRUE;
  958. $this->configure();
  959. $table = fORM::tablize($class);
  960. if (!$schema->getKeys($table, 'primary')) {
  961. throw new fProgrammerException(
  962. 'The database table %1$s (being modelled by the class %2$s) does not appear to have a primary key defined. %3$s and %4$s will not work properly without a primary key.',
  963. $table,
  964. $class,
  965. 'fActiveRecord',
  966. 'fRecordSet'
  967. );
  968. }
  969. // If the configuration was forced, prevent the post::__construct() hook from
  970. // being triggered since it is not really a real record instantiation
  971. $trace = array_slice(debug_backtrace(), 0, 2);
  972. $is_forced = sizeof($trace) == 2;
  973. $is_forced = $is_forced && $trace[1]['function'] == 'forceConfigure';
  974. $is_forced = $is_forced && isset($trace[1]['class']);
  975. $is_forced = $is_forced && $trace[1]['type'] == '::';
  976. $is_forced = $is_forced && in_array($trace[1]['class'], array('fActiveRecord', $class));
  977. if ($is_forced) {
  978. return;
  979. }
  980. }
  981. if (!isset(self::$callback_cache[$class]['__construct'])) {
  982. if (!isset(self::$callback_cache[$class])) {
  983. self::$callback_cache[$class] = array();
  984. }
  985. $callback = fORM::getActiveRecordMethod($class, '__construct');
  986. self::$callback_cache[$class]['__construct'] = $callback ? $callback : FALSE;
  987. }
  988. if ($callback = self::$callback_cache[$class]['__construct']) {
  989. return $this->__call($callback);
  990. }
  991. // Handle loading by a result object passed via the fRecordSet class
  992. if ($key instanceof Iterator) {
  993. $this->loadFromResult($key);
  994. // Handle loading an object from the database
  995. } elseif ($key !== NULL) {
  996. $table = fORM::tablize($class);
  997. $pk_columns = $schema->getKeys($table, 'primary');
  998. // If the primary key does not look properly formatted, check to see if it is a UNIQUE key
  999. $is_unique_key = FALSE;
  1000. if (is_array($key) && (sizeof($pk_columns) == 1 || array_diff(array_keys($key), $pk_columns))) {
  1001. $unique_keys = $schema->getKeys($table, 'unique');
  1002. $key_keys = array_keys($key);
  1003. foreach ($unique_keys as $unique_key) {
  1004. if (!array_diff($key_keys, $unique_key)) {
  1005. $is_unique_key = TRUE;
  1006. }
  1007. }
  1008. }
  1009. $wrong_keys = is_array($key) && (count($key) != count($pk_columns) || array_diff(array_keys($key), $pk_columns));
  1010. $wrong_type = !is_array($key) && (sizeof($pk_columns) != 1 || !is_scalar($key));
  1011. // If we didn't find a UNIQUE key and primary key doesn't look right we fail
  1012. if (!$is_unique_key && ($wrong_keys || $wrong_type)) {
  1013. throw new fProgrammerException(
  1014. 'An invalidly formatted primary or unique key was passed to this %s object',
  1015. fORM::getRecordName($class)
  1016. );
  1017. }
  1018. if ($is_unique_key) {
  1019. $result = $this->fetchResultFromUniqueKey($key);
  1020. $this->loadFromResult($result);
  1021. } else {
  1022. $hash = self::hash($key, $class);
  1023. if (!$this->loadFromIdentityMap($key, $hash)) {
  1024. // Assign the primary key values for loading
  1025. if (is_array($key)) {
  1026. foreach ($pk_columns as $pk_column) {
  1027. $this->values[$pk_column] = $key[$pk_column];
  1028. }
  1029. } else {
  1030. $this->values[$pk_columns[0]] = $key;
  1031. }
  1032. $this->load();
  1033. }
  1034. }
  1035. // Create an empty array for new objects
  1036. } else {
  1037. $column_info = $schema->getColumnInfo(fORM::tablize($class));
  1038. foreach ($column_info as $column => $info) {
  1039. $this->values[$column] = NULL;
  1040. if ($info['default'] !== NULL) {
  1041. self::assign(
  1042. $this->values,
  1043. $this->old_values,
  1044. $column,
  1045. fORM::objectify($class, $column, $info['default'])
  1046. );
  1047. }
  1048. }
  1049. }
  1050. fORM::callHookCallbacks(
  1051. $this,
  1052. 'post::__construct()',
  1053. $this->values,
  1054. $this->old_values,
  1055. $this->related_records,
  1056. $this->cache
  1057. );
  1058. }
  1059. /**
  1060. * All requests that hit this method should be requests for callbacks
  1061. *
  1062. * @internal
  1063. *
  1064. * @param string $method The method to create a callback for
  1065. * @return callback The callback for the method requested
  1066. */
  1067. public function __get($method)
  1068. {
  1069. return array($this, $method);
  1070. }
  1071. /**
  1072. * Configure itself when coming out of the session. Records from the session are NOT hooked into the identity map.
  1073. *
  1074. * @internal
  1075. *
  1076. * @return void
  1077. */
  1078. public function __wakeup()
  1079. {
  1080. $class = get_class($this);
  1081. if (!isset(self::$configured[$class])) {
  1082. $this->configure();
  1083. self::$configured[$class] = TRUE;
  1084. }
  1085. }
  1086. /**
  1087. * Allows the programmer to set features for the class
  1088. *
  1089. * This method is only called once per page load for each class.
  1090. *
  1091. * @return void
  1092. */
  1093. protected function configure()
  1094. {
  1095. }
  1096. /**
  1097. * Creates the fDatabase::translatedQuery() insert statement params
  1098. *
  1099. * @return array The parameters for an fDatabase::translatedQuery() SQL insert statement
  1100. */
  1101. protected function constructInsertParams()
  1102. {
  1103. $columns = array();
  1104. $values = array();
  1105. $column_placeholders = array();
  1106. $value_placeholders = array();
  1107. $class = get_class($this);
  1108. $schema = fORMSchema::retrieve($class);
  1109. $table = fORM::tablize($class);
  1110. $column_info = $schema->getColumnInfo($table);
  1111. foreach ($column_info as $column => $info) {
  1112. if ($schema->getColumnInfo($table, $column, 'auto_increment') && $schema->getColumnInfo($table, $column, 'not_null') && $this->values[$column] === NULL) {
  1113. continue;
  1114. }
  1115. $value = fORM::scalarize($class, $column, $this->values[$column]);
  1116. if ($value === NULL && $info['not_null'] && $info['default'] !== NULL) {
  1117. $value = $info['default'];
  1118. }
  1119. $columns[] = $column;
  1120. $values[] = $value;
  1121. $column_placeholders[] = '%r';
  1122. $value_placeholders[] = $info['placeholder'];
  1123. }
  1124. $sql = 'INSERT INTO %r (' . join(', ', $column_placeholders) . ') VALUES (' . join(', ', $value_placeholders) . ')';
  1125. $params = array($sql, $table);
  1126. $params = array_merge($params, $columns);
  1127. $params = array_merge($params, $values);
  1128. return $params;
  1129. }
  1130. /**
  1131. * Creates the fDatabase::translatedQuery() update statement params
  1132. *
  1133. * @return array The parameters for an fDatabase::translatedQuery() SQL update statement
  1134. */
  1135. protected function constructUpdateParams()
  1136. {
  1137. $class = get_class($this);
  1138. $schema = fORMSchema::retrieve($class);
  1139. $table = fORM::tablize($class);
  1140. $column_info = $schema->getColumnInfo($table);
  1141. $assignments = array();
  1142. $params = array($table);
  1143. foreach ($column_info as $column => $info) {
  1144. if ($info['auto_increment'] && !fActiveRecord::changed($this->values, $this->old_values, $column) && count($column_info) > 1) {
  1145. continue;
  1146. }
  1147. $assignments[] = '%r = ' . $info['placeholder'];
  1148. $value = fORM::scalarize($class, $column, $this->values[$column]);
  1149. if ($value === NULL && $info['not_null'] && $info['default'] !== NULL) {
  1150. $value = $info['default'];
  1151. }
  1152. $params[] = $column;
  1153. $params[] = $value;
  1154. }
  1155. $sql = 'UPDATE %r SET ' . join(', ', $assignments) . ' WHERE ';
  1156. array_unshift($params, $sql);
  1157. return fORMDatabase::addPrimaryKeyWhereParams($schema, $params, $table, $table, $this->values, $this->old_values);
  1158. }
  1159. /**
  1160. * Deletes a record from the database, but does not destroy the object
  1161. *
  1162. * This method will start a database transaction if one is not already active.
  1163. *
  1164. * @param boolean $force_cascade When TRUE, this will cause all child objects to be deleted, even if the ON DELETE clause is RESTRICT or NO ACTION
  1165. * @return fActiveRecord The record object, to allow for method chaining
  1166. */
  1167. public function delete($force_cascade=FALSE)
  1168. {
  1169. // This flag prevents recursive relationships, such as one-to-one
  1170. // relationships, from creating infinite loops
  1171. if (!empty($this->cache['fActiveRecord::delete()::being_deleted'])) {
  1172. return;
  1173. }
  1174. $class = get_class($this);
  1175. if (fORM::getActiveRecordMethod($class, 'delete')) {
  1176. return $this->__call('delete', array());
  1177. }
  1178. if (!$this->exists()) {
  1179. throw new fProgrammerException(
  1180. 'This %s object does not yet exist in the database, and thus can not be deleted',
  1181. fORM::getRecordName($class)
  1182. );
  1183. }
  1184. $db = fORMDatabase::retrieve($class, 'write');
  1185. $schema = fORMSchema::retrieve($class);
  1186. fORM::callHookCallbacks(
  1187. $this,
  1188. 'pre::delete()',
  1189. $this->values,
  1190. $this->old_values,
  1191. $this->related_records,
  1192. $this->cache
  1193. );
  1194. $table = fORM::tablize($class);
  1195. $inside_db_transaction = $db->isInsideTransaction();
  1196. try {
  1197. if (!$inside_db_transaction) {
  1198. $db->translatedQuery('BEGIN');
  1199. }
  1200. fORM::callHookCallbacks(
  1201. $this,
  1202. 'post-begin::delete()',
  1203. $this->values,
  1204. $this->old_values,
  1205. $this->related_records,
  1206. $this->cache
  1207. );
  1208. // Check to ensure no foreign dependencies prevent deletion
  1209. $one_to_one_relationships = $schema->getRelationships($table, 'one-to-one');
  1210. $one_to_many_relationships = $schema->getRelationships($table, 'one-to-many');
  1211. $many_to_many_relationships = $schema->getRelationships($table, 'many-to-many');
  1212. $relationships = array_merge($one_to_one_relationships, $one_to_many_relationships, $many_to_many_relationships);
  1213. $records_sets_to_delete = array();
  1214. $restriction_messages = array();
  1215. $this->cache['fActiveRecord::delete()::being_deleted'] = TRUE;
  1216. foreach ($relationships as $relationship) {
  1217. // Figure out how to check for related records
  1218. if (isset($relationship['join_table'])) {
  1219. $type = 'many-to-many';
  1220. } else {
  1221. $type = in_array($relationship, $one_to_one_relationships) ? 'one-to-one' : 'one-to-many';
  1222. }
  1223. $route = fORMSchema::getRouteNameFromRelationship($type, $relationship);
  1224. $related_class = fORM::classize($relationship['related_table']);
  1225. if ($type == 'one-to-one') {
  1226. $method = 'create' . $related_class;
  1227. $related_record = $this->$method($route);
  1228. if (!$related_record->exists()) {
  1229. continue;
  1230. }
  1231. } else {
  1232. $method = 'build' . fGrammar::pluralize($related_class);
  1233. $record_set = $this->$method($route);
  1234. if (!$record_set->count()) {
  1235. continue;
  1236. }
  1237. if ($type == 'one-to-many' && $relationship['on_delete'] == 'cascade') {
  1238. $records_sets_to_delete[] = $record_set;
  1239. }
  1240. }
  1241. // If we are focing the cascade w…

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