PageRenderTime 68ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/classphp/flourish/fActiveRecord.php

https://github.com/jsuarez/Lexer
PHP | 2603 lines | 1584 code | 428 blank | 591 comment | 365 complexity | d1c640ab2b1ebdece3e32da01731f6a2 MD5 | raw 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-2009 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.0b45
  19. * @changes 1.0.0b45 Added support for `!~`, `&~`, `><` and OR comparisons to ::checkConditions(), made object handling in ::checkConditions() more robust [wb, 2009-09-21]
  20. * @changes 1.0.0b44 Updated code for new fValidationException API [wb, 2009-09-18]
  21. * @changes 1.0.0b43 Updated code for new fRecordSet API [wb, 2009-09-16]
  22. * @changes 1.0.0b42 Corrected a grammar bug in ::hash() [wb, 2009-09-09]
  23. * @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]
  24. * @changes 1.0.0b40 Added a check to the configuration part of ::__construct() to ensure modelled tables have primary keys [wb, 2009-08-26]
  25. * @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]
  26. * @changes 1.0.0b38 Updated ::changed() to do a strict comparison when at least one value is NULL [wb, 2009-08-17]
  27. * @changes 1.0.0b37 Changed ::__construct() to allow any Iterator object instead of just fResult [wb, 2009-08-12]
  28. * @changes 1.0.0b36 Fixed a bug with setting NULL values from v1.0.0b33 [wb, 2009-08-10]
  29. * @changes 1.0.0b35 Fixed a bug with unescaping data in ::loadFromResult() from v1.0.0b33 [wb, 2009-08-10]
  30. * @changes 1.0.0b34 Added the ability to compare fActiveRecord objects in ::checkConditions() [wb, 2009-08-07]
  31. * @changes 1.0.0b33 Performance enhancements to ::__call() and ::__construct() [wb, 2009-08-07]
  32. * @changes 1.0.0b32 Changed ::delete() to remove auto-incrementing primary keys after the post::delete() hook [wb, 2009-07-29]
  33. * @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]
  34. * @changes 1.0.0b30 Updated ::reflect() for new fORM::callReflectCallbacks() API [wb, 2009-07-13]
  35. * @changes 1.0.0b29 Updated to use new fORM::callInspectCallbacks() method [wb, 2009-07-13]
  36. * @changes 1.0.0b28 Fixed a bug where records would break the identity map at the end of ::store() [wb, 2009-07-09]
  37. * @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]
  38. * @changes 1.0.0b26 Added ::checkConditions() from fRecordSet [wb, 2009-07-08]
  39. * @changes 1.0.0b25 Updated ::validate() to use new fORMValidation API, including new message search/replace functionality [wb, 2009-07-01]
  40. * @changes 1.0.0b24 Changed ::validate() to remove duplicate validation messages [wb, 2009-06-30]
  41. * @changes 1.0.0b23 Updated code for new fORMValidation::validateRelated() API [wb, 2009-06-26]
  42. * @changes 1.0.0b22 Added support for the $formatting parameter to encode methods on char, text and varchar columns [wb, 2009-06-19]
  43. * @changes 1.0.0b21 Performance tweaks and updates for fORM and fORMRelated API changes [wb, 2009-06-15]
  44. * @changes 1.0.0b20 Changed replacement values in preg_replace() calls to be properly escaped [wb, 2009-06-11]
  45. * @changes 1.0.0b19 Added `list{RelatedRecords}()` methods, updated code for new fORMRelated API [wb, 2009-06-02]
  46. * @changes 1.0.0b18 Changed ::store() to use new fORMRelated::store() method [wb, 2009-06-02]
  47. * @changes 1.0.0b17 Added some missing parameter information to ::reflect() [wb, 2009-06-01]
  48. * @changes 1.0.0b16 Fixed bugs in ::__clone() and ::replicate() related to recursive relationships [wb-imarc, 2009-05-20]
  49. * @changes 1.0.0b15 Fixed an incorrect variable reference in ::store() [wb, 2009-05-06]
  50. * @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]
  51. * @changes 1.0.0b13 ::delete(), ::load(), ::populate() and ::store() now return the record to allow for method chaining [wb, 2009-03-23]
  52. * @changes 1.0.0b12 ::set() now removes commas from integers and floats to prevent validation issues [wb, 2009-03-22]
  53. * @changes 1.0.0b11 ::encode() no longer adds commas to floats [wb, 2009-03-22]
  54. * @changes 1.0.0b10 ::__wakeup() no longer registers the record as the definitive copy in the identity map [wb, 2009-03-22]
  55. * @changes 1.0.0b9 Changed ::__construct() to populate database default values when a non-existing record is instantiated [wb, 2009-01-12]
  56. * @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]
  57. * @changes 1.0.0b7 Fixed ::__construct() to not trigger the post::__construct() hook when force-configured [wb, 2008-12-30]
  58. * @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]
  59. * @changes 1.0.0b5 Fixed ::replicate() to use plural record names for related records [wb, 2008-12-12]
  60. * @changes 1.0.0b4 Added ::replicate() to allow cloning along with related records [wb, 2008-12-12]
  61. * @changes 1.0.0b3 Changed ::__clone() to clone objects contains in the values and cache arrays [wb, 2008-12-11]
  62. * @changes 1.0.0b2 Added the ::__clone() method to properly duplicate a record [wb, 2008-12-04]
  63. * @changes 1.0.0b The initial implementation [wb, 2007-08-04]
  64. */
  65. abstract class fActiveRecord
  66. {
  67. // The following constants allow for nice looking callbacks to static methods
  68. const assign = 'fActiveRecord::assign';
  69. const changed = 'fActiveRecord::changed';
  70. const checkConditions = 'fActiveRecord::checkConditions';
  71. const forceConfigure = 'fActiveRecord::forceConfigure';
  72. const hasOld = 'fActiveRecord::hasOld';
  73. const reset = 'fActiveRecord::reset';
  74. const retrieveOld = 'fActiveRecord::retrieveOld';
  75. /**
  76. * Caches callbacks for methods
  77. *
  78. * @var array
  79. */
  80. static protected $callback_cache = array();
  81. /**
  82. * An array of flags indicating a class has been configured
  83. *
  84. * @var array
  85. */
  86. static protected $configured = array();
  87. /**
  88. * Maps objects via their primary key
  89. *
  90. * @var array
  91. */
  92. static protected $identity_map = array();
  93. /**
  94. * Caches method name parsings
  95. *
  96. * @var array
  97. */
  98. static protected $method_name_cache = array();
  99. /**
  100. * Keeps track of the recursive call level of replication so we can clear the map
  101. *
  102. * @var integer
  103. */
  104. static protected $replicate_level = 0;
  105. /**
  106. * Keeps a list of records that have been replicated
  107. *
  108. * @var array
  109. */
  110. static protected $replicate_map = array();
  111. /**
  112. * Contains a list of what columns in each class need to be unescaped and what data type they are
  113. *
  114. * @var array
  115. */
  116. static protected $unescape_map = array();
  117. /**
  118. * Sets a value to the `$values` array, preserving the old value in `$old_values`
  119. *
  120. * @internal
  121. *
  122. * @param array &$values The current values
  123. * @param array &$old_values The old values
  124. * @param string $column The column to set
  125. * @param mixed $value The value to set
  126. * @return void
  127. */
  128. static public function assign(&$values, &$old_values, $column, $value)
  129. {
  130. if (!isset($old_values[$column])) {
  131. $old_values[$column] = array();
  132. }
  133. $old_values[$column][] = $values[$column];
  134. $values[$column] = $value;
  135. }
  136. /**
  137. * Checks to see if a value has changed
  138. *
  139. * @internal
  140. *
  141. * @param array &$values The current values
  142. * @param array &$old_values The old values
  143. * @param string $column The column to check
  144. * @return boolean If the value for the column specified has changed
  145. */
  146. static public function changed(&$values, &$old_values, $column)
  147. {
  148. if (!isset($old_values[$column])) {
  149. return FALSE;
  150. }
  151. // We do a strict comparison when one of the values is NULL since
  152. // NULL is almost always meant to be distinct from 0, FALSE, etc
  153. if ($old_values[$column][0] === NULL || $values[$column] === NULL) {
  154. return $old_values[$column][0] !== $values[$column];
  155. }
  156. return $old_values[$column][0] != $values[$column];
  157. }
  158. /**
  159. * Checks to see if a record matches a condition
  160. *
  161. * @internal
  162. *
  163. * @param string $operator The record to check
  164. * @param mixed $value The value to compare to
  165. * @param mixed $result The result of the method call(s)
  166. * @return boolean If the comparison was successful
  167. */
  168. static private function checkCondition($operator, $value, $result)
  169. {
  170. $was_array = is_array($value);
  171. if (!$was_array) { $value = array($value); }
  172. foreach ($value as $i => $_value) {
  173. if (is_object($_value)) {
  174. if ($_value instanceof fActiveRecord) {
  175. continue;
  176. }
  177. if (method_exists($_value, '__toString')) {
  178. $value[$i] = $_value->__toString();
  179. }
  180. }
  181. }
  182. if (!$was_array) { $value = $value[0]; }
  183. $was_array = is_array($result);
  184. if (!$was_array) { $result = array($result); }
  185. foreach ($result as $i => $_result) {
  186. if (is_object($_result)) {
  187. if ($_result instanceof fActiveRecord) {
  188. continue;
  189. }
  190. if (method_exists($_result, '__toString')) {
  191. $result[$i] = $_result->__toString();
  192. }
  193. }
  194. }
  195. if (!$was_array) { $result = $result[0]; }
  196. $match_all = $operator == '&~';
  197. $negate_like = $operator == '!~';
  198. switch ($operator) {
  199. case '&~':
  200. case '!~':
  201. case '~':
  202. if (!$match_all && !$negate_like && !is_array($value) && is_array($result)) {
  203. $value = fORMDatabase::parseSearchTerms($value, TRUE);
  204. }
  205. settype($value, 'array');
  206. settype($result, 'array');
  207. if (count($result) > 1) {
  208. foreach ($value as $_value) {
  209. $found = FALSE;
  210. foreach ($result as $_result) {
  211. if (fUTF8::ipos($_result, $_value) !== FALSE) {
  212. $found = TRUE;
  213. }
  214. }
  215. if (!$found) {
  216. return FALSE;
  217. }
  218. }
  219. } else {
  220. $found = FALSE;
  221. foreach ($value as $_value) {
  222. if (fUTF8::ipos($result[0], $_value) !== FALSE) {
  223. $found = TRUE;
  224. } elseif ($match_all) {
  225. return FALSE;
  226. }
  227. }
  228. if ((!$negate_like && !$found) || ($negate_like && $found)) {
  229. return FALSE;
  230. }
  231. }
  232. break;
  233. case '=':
  234. if ($value instanceof fActiveRecord && $result instanceof fActiveRecord) {
  235. if (get_class($value) != get_class($result) || !$value->exists() || !$result->exists() || self::hash($value) != self::hash($result)) {
  236. return FALSE;
  237. }
  238. } elseif (is_array($value) && !in_array($result, $value)) {
  239. return FALSE;
  240. } elseif (!is_array($value) && $result != $value) {
  241. return FALSE;
  242. }
  243. break;
  244. case '!':
  245. if ($value instanceof fActiveRecord && $result instanceof fActiveRecord) {
  246. if (get_class($value) == get_class($result) && $value->exists() && $result->exists() && self::hash($value) == self::hash($result)) {
  247. return FALSE;
  248. }
  249. } elseif (is_array($value) && in_array($result, $value)) {
  250. return FALSE;
  251. } elseif (!is_array($value) && $result == $value) {
  252. return FALSE;
  253. }
  254. break;
  255. case '<':
  256. if ($result >= $value) {
  257. return FALSE;
  258. }
  259. break;
  260. case '<=':
  261. if ($result > $value) {
  262. return FALSE;
  263. }
  264. break;
  265. case '>':
  266. if ($result <= $value) {
  267. return FALSE;
  268. }
  269. break;
  270. case '>=':
  271. if ($result < $value) {
  272. return FALSE;
  273. }
  274. break;
  275. }
  276. return TRUE;
  277. }
  278. /**
  279. * Checks to see if a record matches all of the conditions
  280. *
  281. * @internal
  282. *
  283. * @param fActiveRecord $record The record to check
  284. * @param array $conditions The conditions to check - see fRecordSet::filter() for format details
  285. * @return boolean If the record meets all conditions
  286. */
  287. static public function checkConditions($record, $conditions)
  288. {
  289. foreach ($conditions as $method => $value) {
  290. // Split the operator off of the end of the method name
  291. if (in_array(substr($method, -2), array('<=', '>=', '!=', '<>', '!~', '&~', '><'))) {
  292. $operator = strtr(
  293. substr($method, -2),
  294. array(
  295. '<>' => '!',
  296. '!=' => '!'
  297. )
  298. );
  299. $method = substr($method, 0, -2);
  300. } else {
  301. $operator = substr($method, -1);
  302. $method = substr($method, 0, -1);
  303. }
  304. if (preg_match('#(?<!\|)\|(?!\|)#', $method)) {
  305. $methods = explode('|', $method);
  306. $values = $value;
  307. $operators = array();
  308. foreach ($methods as &$_method) {
  309. if (in_array(substr($_method, -2), array('<=', '>=', '!=', '<>', '!~', '&~', '><'))) {
  310. $operators[] = strtr(
  311. substr($_method, -2),
  312. array(
  313. '<>' => '!',
  314. '!=' => '!'
  315. )
  316. );
  317. $_method = substr($_method, 0, -2);
  318. } elseif (!ctype_alnum(substr($_method, -1))) {
  319. $operators[] = substr($_method, -1);
  320. $_method = substr($_method, 0, -1);
  321. }
  322. }
  323. $operators[] = $operator;
  324. if (sizeof($operators) == 1) {
  325. // Handle fuzzy searches
  326. if ($operator == '~') {
  327. $results = array();
  328. foreach ($methods as $method) {
  329. $results[] = $record->$method();
  330. }
  331. if (!self::checkCondition($operator, $value, $results)) {
  332. return FALSE;
  333. }
  334. // Handle intersection
  335. } elseif ($operator == '><') {
  336. if (sizeof($methods) != 2 || sizeof($values) != 2) {
  337. throw new fProgrammerException(
  338. 'The intersection operator, %s, requires exactly two methods and two values',
  339. $operator
  340. );
  341. }
  342. $results = array();
  343. $results[0] = $record->{$methods[0]}();
  344. $results[1] = $record->{$methods[1]}();
  345. if ($results[1] === NULL && $values[1] === NULL) {
  346. if (!self::checkCondition('=', $values[0], $results[0])) {
  347. return FALSE;
  348. }
  349. } else {
  350. $starts_between_values = FALSE;
  351. $overlaps_value_1 = FALSE;
  352. if ($values[1] !== NULL) {
  353. $start_lt_value_1 = self::checkCondition('<', $values[0], $results[0]);
  354. $start_gt_value_2 = self::checkCondition('>', $values[1], $results[0]);
  355. $starts_between_values = !$start_lt_value_1 && !$start_gt_value_2;
  356. }
  357. if ($results[1] !== NULL) {
  358. $start_gt_value_1 = self::checkCondition('>', $values[0], $results[0]);
  359. $end_lt_value_1 = self::checkCondition('<', $values[0], $results[1]);
  360. $overlaps_value_1 = !$start_gt_value_1 && !$end_lt_value_1;
  361. }
  362. if (!$starts_between_values && !$overlaps_value_1) {
  363. return FALSE;
  364. }
  365. }
  366. } else {
  367. throw new fProgrammerException(
  368. 'An invalid comparison operator, %s, was specified for multiple columns',
  369. $operator
  370. );
  371. }
  372. // Handle OR conditions
  373. } else {
  374. if (sizeof($methods) != sizeof($values)) {
  375. throw new fProgrammerException(
  376. 'When performing an %1$s comparison there must be an equal number of methods and values, however there are not',
  377. 'OR',
  378. sizeof($methods),
  379. sizeof($values)
  380. );
  381. }
  382. if (sizeof($methods) != sizeof($operators)) {
  383. throw new fProgrammerException(
  384. 'When performing an %s comparison there must be a comparison operator for each column, however one or more is missing',
  385. 'OR'
  386. );
  387. }
  388. $results = array();
  389. $iterations = sizeof($methods);
  390. for ($i=0; $i<$iterations; $i++) {
  391. $results[] = self::checkCondition($operators[$i], $values[$i], $record->{$methods[$i]}());
  392. }
  393. if (!array_filter($results)) {
  394. return FALSE;
  395. }
  396. }
  397. // Single method comparisons
  398. } else {
  399. $result = $record->$method();
  400. if (!self::checkCondition($operator, $value, $result)) {
  401. return FALSE;
  402. }
  403. }
  404. }
  405. return TRUE;
  406. }
  407. /**
  408. * Composes text using fText if loaded
  409. *
  410. * @param string $message The message to compose
  411. * @param mixed $component A string or number to insert into the message
  412. * @param mixed ...
  413. * @return string The composed and possible translated message
  414. */
  415. static protected function compose($message)
  416. {
  417. $args = array_slice(func_get_args(), 1);
  418. if (class_exists('fText', FALSE)) {
  419. return call_user_func_array(
  420. array('fText', 'compose'),
  421. array($message, $args)
  422. );
  423. } else {
  424. return vsprintf($message, $args);
  425. }
  426. }
  427. /**
  428. * Ensures that ::configure() has been called for the class
  429. *
  430. * @internal
  431. *
  432. * @param string $class The class to configure
  433. * @return void
  434. */
  435. static public function forceConfigure($class)
  436. {
  437. if (isset(self::$configured[$class])) {
  438. return;
  439. }
  440. new $class();
  441. }
  442. /**
  443. * Takes a row of data or a primary key and makes a hash from the primary key
  444. *
  445. * @internal
  446. *
  447. * @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
  448. * @param string $class The class name, if $record isn't an fActiveRecord
  449. * @return string|NULL A hash of the record's primary key value or NULL if the record doesn't exist yet
  450. */
  451. static public function hash($record, $class=NULL)
  452. {
  453. if ($record instanceof fActiveRecord && !$record->exists()) {
  454. return NULL;
  455. }
  456. if ($class === NULL) {
  457. if (!$record instanceof fActiveRecord) {
  458. throw new fProgrammerException(
  459. 'The class of the record must be provided if the record specified is not an instance of fActiveRecord'
  460. );
  461. }
  462. $class = get_class($record);
  463. }
  464. $pk_columns = fORMSchema::retrieve()->getKeys(fORM::tablize($class), 'primary');
  465. // Build an array of just the primary key data
  466. $pk_data = array();
  467. foreach ($pk_columns as $pk_column) {
  468. if ($record instanceof fActiveRecord) {
  469. $value = (self::hasOld($record->old_values, $pk_column)) ? self::retrieveOld($record->old_values, $pk_column) : $record->values[$pk_column];
  470. } elseif (is_array($record)) {
  471. $value = $record[$pk_column];
  472. } else {
  473. $value = $record;
  474. }
  475. $pk_data[$pk_column] = fORM::scalarize(
  476. $class,
  477. $pk_column,
  478. $value
  479. );
  480. if (is_numeric($pk_data[$pk_column]) || is_object($pk_data[$pk_column])) {
  481. $pk_data[$pk_column] = (string) $pk_data[$pk_column];
  482. }
  483. }
  484. return md5(serialize($pk_data));
  485. }
  486. /**
  487. * Checks to see if an old value exists for a column
  488. *
  489. * @internal
  490. *
  491. * @param array &$old_values The old values
  492. * @param string $column The column to set
  493. * @return boolean If an old value for that column exists
  494. */
  495. static public function hasOld(&$old_values, $column)
  496. {
  497. return array_key_exists($column, $old_values);
  498. }
  499. /**
  500. * Resets the configuration of the class
  501. *
  502. * @internal
  503. *
  504. * @return void
  505. */
  506. static public function reset()
  507. {
  508. self::$callback_cache = array();
  509. self::$configured = array();
  510. self::$identity_map = array();
  511. self::$method_name_cache = array();
  512. self::$unescape_map = array();
  513. }
  514. /**
  515. * Retrieves the oldest value for a column or all old values
  516. *
  517. * @internal
  518. *
  519. * @param array &$old_values The old values
  520. * @param string $column The column to get
  521. * @param mixed $default The default value to return if no value exists
  522. * @param boolean $return_all Return the array of all old values for this column instead of just the oldest
  523. * @return mixed The old value for the column
  524. */
  525. static public function retrieveOld(&$old_values, $column, $default=NULL, $return_all=FALSE)
  526. {
  527. if (!isset($old_values[$column])) {
  528. return $default;
  529. }
  530. if ($return_all === TRUE) {
  531. return $old_values[$column];
  532. }
  533. return $old_values[$column][0];
  534. }
  535. /**
  536. * A data store for caching data related to a record, the structure of this is completely up to the developer using it
  537. *
  538. * @var array
  539. */
  540. protected $cache = array();
  541. /**
  542. * The old values for this record
  543. *
  544. * Column names are the keys, but a column key will only be present if a
  545. * value has changed. The value associated with each key is an array of
  546. * old values with the first entry being the oldest value. The static
  547. * methods ::assign(), ::changed(), ::hasOld() and ::retrieveOld() are the
  548. * best way to interact with this array.
  549. *
  550. * @var array
  551. */
  552. protected $old_values = array();
  553. /**
  554. * Records that are related to the current record via some relationship
  555. *
  556. * This array is used to cache related records so that a database query
  557. * is not required each time related records are accessed. The fORMRelated
  558. * class handles most of the interaction with this array.
  559. *
  560. * @var array
  561. */
  562. protected $related_records = array();
  563. /**
  564. * The values for this record
  565. *
  566. * This array always contains every column in the database table as a key
  567. * with the value being the current value.
  568. *
  569. * @var array
  570. */
  571. protected $values = array();
  572. /**
  573. * Handles all method calls for columns, related records and hook callbacks
  574. *
  575. * Dynamically handles `get`, `set`, `prepare`, `encode` and `inspect`
  576. * methods for each column in this record. Method names are in the form
  577. * `verbColumName()`.
  578. *
  579. * This method also handles `associate`, `build`, `count` and `link` verbs
  580. * for records in many-to-many relationships; `build`, `count` and
  581. * `populate` verbs for all related records in one-to-many relationships
  582. * and the `create` verb for all related records in *-to-one relationships.
  583. *
  584. * Method callbacks registered through fORM::registerActiveRecordMethod()
  585. * will be delegated via this method.
  586. *
  587. * @param string $method_name The name of the method called
  588. * @param array $parameters The parameters passed
  589. * @return mixed The value returned by the method called
  590. */
  591. public function __call($method_name, $parameters)
  592. {
  593. $class = get_class($this);
  594. if (!isset(self::$callback_cache[$class][$method_name])) {
  595. if (!isset(self::$callback_cache[$class])) {
  596. self::$callback_cache[$class] = array();
  597. }
  598. $callback = fORM::getActiveRecordMethod($class, $method_name);
  599. self::$callback_cache[$class][$method_name] = $callback ? $callback : FALSE;
  600. }
  601. if ($callback = self::$callback_cache[$class][$method_name]) {
  602. return call_user_func_array(
  603. $callback,
  604. array(
  605. $this,
  606. &$this->values,
  607. &$this->old_values,
  608. &$this->related_records,
  609. &$this->cache,
  610. $method_name,
  611. $parameters
  612. )
  613. );
  614. }
  615. if (!isset(self::$method_name_cache[$method_name])) {
  616. list ($action, $subject) = fORM::parseMethod($method_name);
  617. self::$method_name_cache[$method_name] = array(
  618. 'action' => $action,
  619. 'subject' => $subject
  620. );
  621. } else {
  622. $action = self::$method_name_cache[$method_name]['action'];
  623. $subject = self::$method_name_cache[$method_name]['subject'];
  624. }
  625. switch ($action) {
  626. // Value methods
  627. case 'get':
  628. return $this->get($subject);
  629. case 'encode':
  630. if (isset($parameters[0])) {
  631. return $this->encode($subject, $parameters[0]);
  632. }
  633. return $this->encode($subject);
  634. case 'prepare':
  635. if (isset($parameters[0])) {
  636. return $this->prepare($subject, $parameters[0]);
  637. }
  638. return $this->prepare($subject);
  639. case 'inspect':
  640. if (isset($parameters[0])) {
  641. return $this->inspect($subject, $parameters[0]);
  642. }
  643. return $this->inspect($subject);
  644. case 'set':
  645. if (sizeof($parameters) < 1) {
  646. throw new fProgrammerException(
  647. 'The method, %s(), requires at least one parameter',
  648. $method_name
  649. );
  650. }
  651. return $this->set($subject, $parameters[0]);
  652. // Related data methods
  653. case 'associate':
  654. if (sizeof($parameters) < 1) {
  655. throw new fProgrammerException(
  656. 'The method, %s(), requires at least one parameter',
  657. $method_name
  658. );
  659. }
  660. $table = fORM::tablize($class);
  661. $records = $parameters[0];
  662. $route = isset($parameters[1]) ? $parameters[1] : NULL;
  663. $plural = FALSE;
  664. // one-to-many relationships need to use plural forms
  665. if (in_array($subject, fORMSchema::retrieve()->getTables())) {
  666. if (fORMSchema::isOneToOne($table, $subject, $route)) {
  667. throw new fProgrammerException(
  668. 'The table %1$s is not in a %2$srelationship with the table %3$s',
  669. $table,
  670. '*-to-many ',
  671. $subject
  672. );
  673. }
  674. $subject = fGrammar::singularize($subject);
  675. $plural = TRUE;
  676. }
  677. $subject = fGrammar::camelize($subject, TRUE);
  678. // This handles one-to-many and many-to-many relationships
  679. if ($plural) {
  680. return fORMRelated::associateRecords($class, $this->related_records, $subject, $records, $route);
  681. }
  682. // This handles one-to-one relationships
  683. return fORMRelated::associateRecord($class, $this->related_records, $subject, $records, $route);
  684. case 'build':
  685. $subject = fGrammar::singularize($subject);
  686. $subject = fGrammar::camelize($subject, TRUE);
  687. if (isset($parameters[0])) {
  688. return fORMRelated::buildRecords($class, $this->values, $this->related_records, $subject, $parameters[0]);
  689. }
  690. return fORMRelated::buildRecords($class, $this->values, $this->related_records, $subject);
  691. case 'count':
  692. $subject = fGrammar::singularize($subject);
  693. $subject = fGrammar::camelize($subject, TRUE);
  694. if (isset($parameters[0])) {
  695. return fORMRelated::countRecords($class, $this->values, $this->related_records, $subject, $parameters[0]);
  696. }
  697. return fORMRelated::countRecords($class, $this->values, $this->related_records, $subject);
  698. case 'create':
  699. $subject = fGrammar::camelize($subject, TRUE);
  700. if (isset($parameters[0])) {
  701. return fORMRelated::createRecord($class, $this->values, $this->related_records, $subject, $parameters[0]);
  702. }
  703. return fORMRelated::createRecord($class, $this->values, $this->related_records, $subject);
  704. case 'inject':
  705. if (sizeof($parameters) < 1) {
  706. throw new fProgrammerException(
  707. 'The method, %s(), requires at least one parameter',
  708. $method_name
  709. );
  710. }
  711. $subject = fGrammar::singularize($subject);
  712. $subject = fGrammar::camelize($subject, TRUE);
  713. if (isset($parameters[1])) {
  714. return fORMRelated::setRecordSet($class, $this->related_records, $subject, $parameters[0], $parameters[1]);
  715. }
  716. return fORMRelated::setRecordSet($class, $this->related_records, $subject, $parameters[0]);
  717. case 'link':
  718. $subject = fGrammar::singularize($subject);
  719. $subject = fGrammar::camelize($subject, TRUE);
  720. if (isset($parameters[0])) {
  721. return fORMRelated::linkRecords($class, $this->related_records, $subject, $parameters[0]);
  722. }
  723. return fORMRelated::linkRecords($class, $this->related_records, $subject);
  724. case 'list':
  725. $subject = fGrammar::singularize($subject);
  726. $subject = fGrammar::camelize($subject, TRUE);
  727. if (isset($parameters[0])) {
  728. return fORMRelated::getPrimaryKeys($class, $this->values, $this->related_records, $subject, $parameters[0]);
  729. }
  730. return fORMRelated::getPrimaryKeys($class, $this->values, $this->related_records, $subject);
  731. case 'populate':
  732. $table = fORM::tablize($class);
  733. $route = isset($parameters[0]) ? $parameters[0] : NULL;
  734. // one-to-many relationships need to use plural forms
  735. if (in_array($subject, fORMSchema::retrieve()->getTables())) {
  736. if (fORMSchema::isOneToOne($table, $subject, $route)) {
  737. throw new fProgrammerException(
  738. 'The table %1$s is not in a%2$srelationship with the table %3$s',
  739. $table,
  740. ' one-to-many ',
  741. $subject
  742. );
  743. }
  744. $subject = fGrammar::singularize($subject);
  745. }
  746. $subject = fGrammar::camelize($subject, TRUE);
  747. return fORMRelated::populateRecords($class, $this->related_records, $subject, $route);
  748. case 'tally':
  749. if (sizeof($parameters) < 1) {
  750. throw new fProgrammerException(
  751. 'The method, %s(), requires at least one parameter',
  752. $method_name
  753. );
  754. }
  755. $subject = fGrammar::singularize($subject);
  756. $subject = fGrammar::camelize($subject, TRUE);
  757. if (isset($parameters[1])) {
  758. return fORMRelated::setCount($class, $this->related_records, $subject, $parameters[0], $parameters[1]);
  759. }
  760. return fORMRelated::setCount($class, $this->related_records, $subject, $parameters[0]);
  761. // Error handler
  762. default:
  763. throw new fProgrammerException(
  764. 'Unknown method, %s(), called',
  765. $method_name
  766. );
  767. }
  768. }
  769. /**
  770. * Creates a clone of a record
  771. *
  772. * If the record has an auto incrementing primary key, the primary key will
  773. * be erased in the clone. If the primary key is not auto incrementing,
  774. * the primary key will be left as-is in the clone. In either situation the
  775. * clone will return `FALSE` from the ::exists() method until ::store() is
  776. * called.
  777. *
  778. * @internal
  779. *
  780. * @return fActiveRecord
  781. */
  782. public function __clone()
  783. {
  784. $class = get_class($this);
  785. // Copy values and cache, making sure objects are cloned to prevent reference issues
  786. $temp_values = $this->values;
  787. $new_values = array();
  788. $this->values =& $new_values;
  789. foreach ($temp_values as $column => $value) {
  790. $this->values[$column] = fORM::replicate($class, $column, $value);
  791. }
  792. $temp_cache = $this->cache;
  793. $new_cache = array();
  794. $this->cache =& $new_cache;
  795. foreach ($temp_cache as $key => $value) {
  796. if (is_object($value)) {
  797. $this->cache[$key] = clone $value;
  798. } else {
  799. $this->cache[$key] = $value;
  800. }
  801. }
  802. // Related records are purged
  803. $new_related_records = array();
  804. $this->related_records =& $new_related_records;
  805. // Old values are changed to look like the record is non-existant
  806. $new_old_values = array();
  807. $this->old_values =& $new_old_values;
  808. foreach (array_keys($this->values) as $key) {
  809. $this->old_values[$key] = array(NULL);
  810. }
  811. // If we have a single auto incrementing primary key, remove the value
  812. $table = fORM::tablize($class);
  813. $pk_columns = fORMSchema::retrieve()->getKeys($table, 'primary');
  814. if (sizeof($pk_columns) == 1 && fORMSchema::retrieve()->getColumnInfo($table, $pk_columns[0], 'auto_increment')) {
  815. $this->values[$pk_columns[0]] = NULL;
  816. unset($this->old_values[$pk_columns[0]]);
  817. }
  818. }
  819. /**
  820. * Creates a new record or loads one from the database - if a primary key or unique key is provided the record will be loaded
  821. *
  822. * @throws fNotFoundException When the record specified by `$key` can not be found in the database
  823. *
  824. * @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}`
  825. * @return fActiveRecord
  826. */
  827. public function __construct($key=NULL)
  828. {
  829. $class = get_class($this);
  830. // If the features of this class haven't been set yet, do it
  831. if (!isset(self::$configured[$class])) {
  832. $this->configure();
  833. self::$configured[$class] = TRUE;
  834. $table = fORM::tablize($class);
  835. if (!fORMSchema::retrieve()->getKeys($table, 'primary')) {
  836. throw new fProgrammerException(
  837. '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.',
  838. $table,
  839. $class,
  840. 'fActiveRecord',
  841. 'fRecordSet'
  842. );
  843. }
  844. // If the configuration was forced, prevent the post::__construct() hook from
  845. // being triggered since it is not really a real record instantiation
  846. $trace = array_slice(debug_backtrace(), 0, 2);
  847. $is_forced = sizeof($trace) == 2;
  848. $is_forced = $is_forced && $trace[1]['function'] == 'forceConfigure';
  849. $is_forced = $is_forced && isset($trace[1]['class']);
  850. $is_forced = $is_forced && $trace[1]['type'] == '::';
  851. $is_forced = $is_forced && in_array($trace[1]['class'], array('fActiveRecord', $class));
  852. if ($is_forced) {
  853. return;
  854. }
  855. }
  856. if (!isset(self::$callback_cache[$class]['__construct'])) {
  857. if (!isset(self::$callback_cache[$class])) {
  858. self::$callback_cache[$class] = array();
  859. }
  860. $callback = fORM::getActiveRecordMethod($class, '__construct');
  861. self::$callback_cache[$class]['__construct'] = $callback ? $callback : FALSE;
  862. }
  863. if ($callback = self::$callback_cache[$class]['__construct']) {
  864. return $this->__call($callback);
  865. }
  866. // Handle loading by a result object passed via the fRecordSet class
  867. if ($key instanceof Iterator) {
  868. if ($this->loadFromResult($key)) {
  869. return;
  870. }
  871. // Handle loading an object from the database
  872. } elseif ($key !== NULL) {
  873. $table = fORM::tablize($class);
  874. $pk_columns = fORMSchema::retrieve()->getKeys($table, 'primary');
  875. // If the primary key does not look properly formatted, check to see if it is a UNIQUE key
  876. $is_unique_key = FALSE;
  877. if (is_array($key) && (sizeof($pk_columns) == 1 || array_diff(array_keys($key), $pk_columns))) {
  878. $unique_keys = fORMSchema::retrieve()->getKeys($table, 'unique');
  879. $key_keys = array_keys($key);
  880. foreach ($unique_keys as $unique_key) {
  881. if (!array_diff($key_keys, $unique_key)) {
  882. $is_unique_key = TRUE;
  883. }
  884. }
  885. }
  886. $wrong_keys = is_array($key) && array_diff(array_keys($key), $pk_columns);
  887. $wrong_type = !is_array($key) && (sizeof($pk_columns) != 1 || !is_scalar($key));
  888. // If we didn't find a UNIQUE key and primary key doesn't look right we fail
  889. if (!$is_unique_key && ($wrong_keys || $wrong_type)) {
  890. throw new fProgrammerException(
  891. 'An invalidly formatted primary or unique key was passed to this %s object',
  892. fORM::getRecordName($class)
  893. );
  894. }
  895. if ($is_unique_key) {
  896. $result = $this->fetchResultFromUniqueKey($key);
  897. if ($this->loadFromResult($result)) {
  898. return;
  899. }
  900. } else {
  901. $hash = self::hash($key, $class);
  902. if ($this->loadFromIdentityMap($key, $hash)) {
  903. return;
  904. }
  905. // Assign the primary key values for loading
  906. if (is_array($key)) {
  907. foreach ($pk_columns as $pk_column) {
  908. $this->values[$pk_column] = $key[$pk_column];
  909. }
  910. } else {
  911. $this->values[$pk_columns[0]] = $key;
  912. }
  913. $this->load();
  914. }
  915. // Create an empty array for new objects
  916. } else {
  917. $column_info = fORMSchema::retrieve()->getColumnInfo(fORM::tablize($class));
  918. foreach ($column_info as $column => $info) {
  919. $this->values[$column] = NULL;
  920. if ($info['default'] !== NULL) {
  921. self::assign(
  922. $this->values,
  923. $this->old_values,
  924. $column,
  925. fORM::objectify($class, $column, $info['default'])
  926. );
  927. }
  928. }
  929. }
  930. fORM::callHookCallbacks(
  931. $this,
  932. 'post::__construct()',
  933. $this->values,
  934. $this->old_values,
  935. $this->related_records,
  936. $this->cache
  937. );
  938. }
  939. /**
  940. * All requests that hit this method should be requests for callbacks
  941. *
  942. * @internal
  943. *
  944. * @param string $method The method to create a callback for
  945. * @return callback The callback for the method requested
  946. */
  947. public function __get($method)
  948. {
  949. return array($this, $method);
  950. }
  951. /**
  952. * Configure itself when coming out of the session. Records from the session are NOT hooked into the identity map.
  953. *
  954. * @internal
  955. *
  956. * @return void
  957. */
  958. public function __wakeup()
  959. {
  960. $class = get_class($this);
  961. if (!isset(self::$configured[$class])) {
  962. $this->configure();
  963. self::$configured[$class] = TRUE;
  964. }
  965. }
  966. /**
  967. * Allows the programmer to set features for the class
  968. *
  969. * This method is only called once per page load for each class.
  970. *
  971. * @return void
  972. */
  973. protected function configure()
  974. {
  975. }
  976. /**
  977. * Creates the SQL to insert this record
  978. *
  979. * @param array $sql_values The SQL-formatted values for this record
  980. * @return string The SQL insert statement
  981. */
  982. protected function constructInsertSQL($sql_values)
  983. {
  984. $sql = 'INSERT INTO ' . fORM::tablize(get_class($this)) . ' (';
  985. $columns = '';
  986. $values = '';
  987. $column_num = 0;
  988. foreach ($sql_values as $column => $sql_value) {
  989. if ($column_num) { $columns .= ', '; $values .= ', '; }
  990. $columns .= $column;
  991. $values .= $sql_value;
  992. $column_num++;
  993. }
  994. $sql .= $columns . ') VALUES (' . $values . ')';
  995. return $sql;
  996. }
  997. /**
  998. * Creates the SQL to update this record
  999. *
  1000. * @param array $sql_values The SQL-formatted values for this record
  1001. * @return string The SQL update statement
  1002. */
  1003. protected function constructUpdateSQL($sql_values)
  1004. {
  1005. $table = fORM::tablize(get_class($this));
  1006. $sql = 'UPDATE ' . $table . ' SET ';
  1007. $column_num = 0;
  1008. foreach ($sql_values as $column => $sql_value) {
  1009. if ($column_num) { $sql .= ', '; }
  1010. $sql .= $column . ' = ' . $sql_value;
  1011. $column_num++;
  1012. }
  1013. $sql .= ' WHERE ' . fORMDatabase::createPrimaryKeyWhereClause($table, $table, $this->values, $this->old_values);
  1014. return $sql;
  1015. }
  1016. /**
  1017. * Deletes a record from the database, but does not destroy the object
  1018. *
  1019. * This method will start a database transaction if one is not already active.
  1020. *
  1021. * @return fActiveRecord The record object, to allow for method chaining
  1022. */
  1023. public function delete()
  1024. {
  1025. $class = get_class($this);
  1026. if (fORM::getActiveRecordMethod($class, 'delete')) {
  1027. return $this->__call('delete', array());
  1028. }
  1029. if (!$this->exists()) {
  1030. throw new fProgrammerException(
  1031. 'This %s object does not yet exist in the database, and thus can not be deleted',
  1032. fORM::getRecordName($class)
  1033. );
  1034. }
  1035. fORM::callHookCallbacks(
  1036. $this,
  1037. 'pre::delete()',
  1038. $this->values,
  1039. $this->old_values,
  1040. $this->related_records,
  1041. $this->cache
  1042. );
  1043. $table = fORM::tablize($class);
  1044. $inside_db_transaction = fORMDatabase::retrieve()->isInsideTransaction();
  1045. try {
  1046. if (!$inside_db_transaction) {
  1047. fORMDatabase::retrieve()->translatedQuery('BEGIN');
  1048. }
  1049. fORM::callHookCallbacks(
  1050. $this,
  1051. 'post-begin::delete()',
  1052. $this->values,
  1053. $this->old_values,
  1054. $this->related_records,
  1055. $this->cache
  1056. );
  1057. // Check to ensure no foreign dependencies prevent deletion
  1058. $one_to_many_relationships = fORMSchema::retrieve()->getRelationships($table, 'one-to-many');
  1059. $many_to_many_relationships = fORMSchema::retrieve()->getRelationships($table, 'many-to-many');
  1060. $relationships = array_merge($one_to_many_relationships, $many_to_many_relationships);
  1061. $records_sets_to_delete = array();
  1062. $restriction_messages = array();
  1063. foreach ($relationships as $relationship) {
  1064. // Figure out how to check for related records
  1065. $type = (isset($relationship['join_table'])) ? 'many-to-many' : 'one-to-many';
  1066. $route = fORMSchema::getRouteNameFromRelationship($type, $relationship);
  1067. $related_class = fORM::classize($relationship['related_table']);
  1068. $related_objects = fGrammar::pluralize($related_class);
  1069. $method = 'build' . $related_objects;
  1070. // Grab the related records
  1071. $record_set = $this->$method($route);
  1072. // If there are none, we can just move on
  1073. if (!$record_set->count()) {
  1074. continue;
  1075. }
  1076. if ($type == 'one-to-many' && $relationship['on_delete'] == 'cascade') {
  1077. $records_sets_to_delete[] = $record_set;
  1078. }
  1079. if ($relationship['on_delete'] == 'restrict' || $relationship['on_delete'] == 'no_action') {
  1080. // Otherwise we have a restriction
  1081. $related_class_name = fORM::classize($relationship['related_table']);
  1082. $related_record_name = fORM::getRecordName($related_class_name);
  1083. $related_record_name = fGrammar::pluralize($related_record_name);
  1084. $restriction_messages[] = self::compose("One or more %s references it", $related_record_name);
  1085. }
  1086. }
  1087. if ($restriction_messages) {
  1088. throw new fValidationException(
  1089. self::compose('This %s can not be deleted because:', fORM::getRecordName($class)),
  1090. $restriction_messages
  1091. );
  1092. }
  1093. // Delete this record
  1094. $sql = 'DELETE FROM ' . $table . ' WHERE ' . fORMDatabase::createPrimaryKeyWhereClause($table, $table, $this->values, $this->old_values);
  1095. $result = fORMDatabase::retrieve()->translatedQuery($sql);
  1096. // Delete related records
  1097. foreach ($records_sets_to_delete as $record_set) {
  1098. foreach ($record_set as $record) {
  1099. if ($record->exists()) {
  1100. $record->delete();
  1101. }
  1102. }
  1103. }
  1104. fORM::callHookCallbacks(
  1105. $this,
  1106. 'pre-commit::delete()',
  1107. $this->values,
  1108. $this->old_values,
  1109. $this->related_records,
  1110. $this->cache
  1111. );
  1112. if (!$inside_db_transaction) {
  1113. fORMDatabase::retrieve()->translatedQuery('COMMIT');
  1114. }
  1115. fORM::callHookCallbacks(
  1116. $this,
  1117. 'post-commit::delete()',
  1118. $this->values,
  1119. $this->old_values,
  1120. $this->related_records,
  1121. $this->cache
  1122. );
  1123. } catch (fException $e) {
  1124. if (!$inside_db_transaction) {
  1125. fORMDatabase::retrieve()->translatedQuery('ROLLBACK');
  1126. }
  1127. fORM::callHookCallbacks(
  1128. $this,
  1129. 'post-rollback::delete()',
  1130. $this->values,
  1131. $this->old_values,
  1132. $this->related_records,
  1133. $this->cache
  1134. );
  1135. // Check to see if the validation exception came from a related record, and fix the message
  1136. if ($e instanceof fValidationException) {
  1137. $message = $e->getMessage();
  1138. $search = self::compose('This %s can not be deleted because:', fORM::getRecordName($class));
  1139. if (stripos($message, $search) === FALSE) {
  1140. $regex = self::compose('This %s can not be deleted because:', '__');
  1141. $regex_parts = explode('__', $regex);
  1142. $regex = '#(' . preg_quote($regex_parts[0], '#') . ').*?(' . preg_quote($regex_parts[0], '#') . ')#';
  1143. $message = preg_replace($regex, '\1' . strtr(fORM::getRecordName($class), array('\\' => '\\\\', '$' => '\\$')) . '\2', $message);
  1144. $find = self::compose("One or more %s references it", '__');
  1145. $find_parts = explode('__', $find);
  1146. $find_regex = '#' . preg_quote($find_parts[0], '#') . '(.*?)' . preg_quote($find_parts[1], '#') . '#';
  1147. $replace = self::compose("One or more %s indirectly references it", '__');
  1148. $replace_parts = explode('__', $replace);
  1149. $replace_regex = strtr($replace_parts[0], array('\\' => '\\\\', '$' => '\\$')) . '\1' . strtr($replace_parts[1], array('\\' => '\\\\', '$' => '\\$'));
  1150. $message = preg_replace($find_regex, $replace_regex, $regex);
  1151. throw new fValidationException($message);
  1152. }
  1153. }
  1154. throw $e;
  1155. }
  1156. fORM::callHookCallbacks(
  1157. $this,
  1158. 'post::delete()',
  1159. $this->values,
  1160. $this->old_values,
  1161. $this->related_records,
  1162. $this->cache
  1163. );
  1164. // If we just deleted an object that has an auto-incrementing primary key,
  1165. // lets delete that value from the object since it is no longer valid
  1166. $pk_columns = fORMSchema::retrieve()->getKeys($table, 'primary');
  1167. if (sizeof($pk_columns) == 1 && fORMSchema::retrieve()->getColumnInfo($table, $pk_columns[0], 'auto_increment')) {
  1168. $this->values[$pk_columns[0]] = NULL;
  1169. unset($this->old_values[$pk_columns[0]]);
  1170. }
  1171. return $this;
  1172. }
  1173. /**
  1174. * Retrieves a value from the record and prepares it for output into an HTML form element.
  1175. *
  1176. * Below are the transformations performed:
  1177. *
  1178. * - **varchar, char, text**: will run through fHTML::encode(), if `TRUE` is passed the text will be run through fHTML::convertNewLinks() and fHTML::makeLinks()
  1179. * - **float**: takes 1 parameter to specify the number of decimal places
  1180. * - **date, time, timestamp**: `format()` will be called on the fDate/fTime/fTimestamp object with the 1 parameter specified
  1181. * - **objects**: the object will be converted to a string by `__toString()` or a `(string)` cast and then will be run through fHTML::encode()
  1182. * - **all other data types**: the value will be run through fHTML::encode()
  1183. *
  1184. * @param string $column The name of the column to retrieve
  1185. * @param string $formatting The formatting string
  1186. * @return string The encoded value for the column specified
  1187. */
  1188. protected function encode($column, $formatting=NULL)
  1189. {
  1190. if (!array_key_exists($column, $this->values)) {
  1191. throw new fProgrammerException(
  1192. 'The column specified, %s, does not exist',
  1193. $column
  1194. );
  1195. }
  1196. $table = fORM::tablize(get_class($this));
  1197. $column_type = fORMSchema::retrieve()->getColumnInfo($table, $column, 'type');
  1198. // Ensure the programmer is calling the function properly
  1199. if ($column_type == 'blob') {
  1200. throw new fProgrammerException(
  1201. 'The column specified, %s, does not support forming because it is a blob column',
  1202. $column
  1203. );
  1204. }
  1205. if ($formatting !== NULL && in_array($column_type, array('boolean', 'integer'))) {
  1206. throw new fProgrammerException(
  1207. 'The column specified, %s, does not support any formatting options',
  1208. $column
  1209. );
  1210. }
  1211. // Grab the value for empty value checking
  1212. $method_name = 'get' . fGrammar::camelize($column, TRUE);
  1213. $value = $this->$method_name();
  1214. // Date/time objects
  1215. if (is_object($value) && in_array($column_type, array('date', 'time', 'timestamp'))) {
  1216. if ($formatting === NULL) {
  1217. throw new fProgrammerException(
  1218. 'The column specified, %s, requires one formatting parameter, a valid date() formatting string',
  1219. $column
  1220. );
  1221. }
  1222. $value = $value->format($formatting);
  1223. }
  1224. // Other objects
  1225. if (is_object($value) && is_callable(array($value, '__toString'))) {
  1226. $value = $value->__toString();
  1227. } elseif (is_object($value)) {
  1228. $value = (string) $value;
  1229. }
  1230. // Make sure we don't mangle a non-float value
  1231. if ($column_type == 'float' && is_numeric($value)) {
  1232. $column_decimal_places = fORMSchema::retrieve()->getColumnInfo($table, $column, 'decimal_places');
  1233. // If the user passed in a formatting value, use it
  1234. if ($formatting !== NULL && is_numeric($formatting)) {
  1235. $decimal_places = (int) $formatting;
  1236. // If the column has a pre-defined number of decimal places, use that
  1237. } elseif ($column_decimal_places !== NULL) {
  1238. $decimal_places = $column_decimal_places;
  1239. // This figures out how many decimal places are part of the current value
  1240. } else {
  1241. $value_parts = explode('.', $value);
  1242. $decimal_places = (!isset($value_parts[1])) ? 0 : strlen($value_parts[1]);
  1243. }
  1244. return number_format($value, $decimal_places, '.', '');
  1245. }
  1246. // Turn line-breaks into breaks for text fields and add links
  1247. if ($formatting === TRUE && in_array($column_type, array('varchar', 'char', 'text'))) {
  1248. return fHTML::makeLinks(fHTML::convertNewlines(fHTML::encode($value)));
  1249. }
  1250. // Anything that has gotten to here is a string value or is not the proper data type for the column that contains it
  1251. return fHTML::encode($value);
  1252. }
  1253. /**
  1254. * Checks to see if the record exists in the database
  1255. *
  1256. * @return boolean If the record exists in the database
  1257. */
  1258. public function exists()
  1259. {
  1260. $class = get_class($this);
  1261. if (fORM::getActiveRecordMethod($class, 'exists')) {
  1262. return $this->__call('exists', array());
  1263. }
  1264. $pk_columns = fORMSchema::retrieve()->getKeys(fORM::tablize($class), 'primary');
  1265. $exists = FALSE;
  1266. foreach ($pk_columns as $pk_column) {
  1267. $has_old = self::hasOld($this->old_values, $pk_column);
  1268. if (($has_old && self::retrieveOld($this->old_values, $pk_column) !== NULL) || (!$has_old && $this->values[$pk_column] !== NULL)) {
  1269. $exists = TRUE;
  1270. }
  1271. }
  1272. return $exists;
  1273. }
  1274. /**
  1275. * Loads a record from the database based on a UNIQUE key
  1276. *
  1277. * @throws fNotFoundException
  1278. *
  1279. * @param array $values The UNIQUE key values to try and load with
  1280. * @return void
  1281. */
  1282. protected function fetchResultFromUniqueKey($values)
  1283. {
  1284. $class = get_class($this);
  1285. try {
  1286. if ($values === array_combine(array_keys($values), array_fill(0, sizeof($values), NULL))) {
  1287. throw new fExpectedException('The values specified for the unique key are all NULL');
  1288. }
  1289. $table = fORM::tablize($class);
  1290. $sql = 'SELECT * FROM ' . $table . ' WHERE ';
  1291. $conditions = array();
  1292. foreach ($values as $column => $value) {
  1293. $conditions[] = $column . fORMDatabase::escapeBySchema($table, $column, $value, '=');
  1294. }
  1295. $sql .= join(' AND ', $conditions);
  1296. $result = fORMDatabase::retrieve()->translatedQuery($sql);
  1297. $result->tossIfNoRows();
  1298. } catch (fExpectedException $e) {
  1299. throw new fNotFoundException(
  1300. 'The %s requested could not be found',
  1301. fORM::getRecordName($class)
  1302. );
  1303. }
  1304. return $result;
  1305. }
  1306. /**
  1307. * Retrieves a value from the record
  1308. *
  1309. * @param string $column The name of the column to retrieve
  1310. * @return mixed The value for the column specified
  1311. */
  1312. protected function get($column)
  1313. {
  1314. if (!isset($this->values[$column]) && !array_key_exists($column, $this->values)) {
  1315. throw new fProgrammerException(
  1316. 'The column specified, %s, does not exist',
  1317. $column
  1318. );
  1319. }
  1320. return $this->values[$column];
  1321. }
  1322. /**
  1323. * Retrieves information about a column
  1324. *
  1325. * @param string $column The name of the column to inspect
  1326. * @param string $element The metadata element to retrieve
  1327. * @return mixed The metadata array for the column, or the metadata element specified
  1328. */
  1329. protected function inspect($column, $element=NULL)
  1330. {
  1331. if (!array_key_exists($column, $this->values)) {
  1332. throw new fProgrammerException(
  1333. 'The column specified, %s, does not exist',
  1334. $column
  1335. );
  1336. }
  1337. $info = fORMSchema::retrieve()->getColumnInfo(fORM::tablize(get_class($this)), $column);
  1338. if (!in_array($info['type'], array('varchar', 'char', 'text'))) {
  1339. unset($info['valid_values']);
  1340. unset($info['max_length']);
  1341. }
  1342. if ($info['type'] != 'float') {
  1343. unset($info['decimal_places']);
  1344. }
  1345. if ($info['type'] != 'integer') {
  1346. unset($info['auto_increment']);
  1347. }
  1348. $info['feature'] = NULL;
  1349. fORM::callInspectCallbacks(get_class($this), $column, $info);
  1350. if ($element) {
  1351. if (!isset($info[$element])) {
  1352. throw new fProgrammerException(
  1353. 'The element specified, %1$s, is invalid. Must be one of: %2$s.',
  1354. $element,
  1355. join(', ', array_keys($info))
  1356. );
  1357. }
  1358. return $info[$element];
  1359. }
  1360. return $info;
  1361. }
  1362. /**
  1363. * Loads a record from the database
  1364. *
  1365. * @throws fNotFoundException When the record could not be found in the database
  1366. *
  1367. * @return fActiveRecord The record object, to allow for method chaining
  1368. */
  1369. public function load()
  1370. {
  1371. $class = get_class($this);
  1372. if (fORM::getActiveRecordMethod($class, 'load')) {
  1373. return $this->__call('load', array());
  1374. }
  1375. try {
  1376. $table = fORM::tablize($class);
  1377. $sql = 'SELECT * FROM ' . $table . ' WHERE ' . fORMDatabase::createPrimaryKeyWhereClause($table, $table, $this->values, $this->old_values);
  1378. $result = fORMDatabase::retrieve()->translatedQuery($sql);
  1379. $result->tossIfNoRows();
  1380. } catch (fExpectedException $e) {
  1381. throw new fNotFoundException(
  1382. 'The %s requested could not be found',
  1383. fORM::getRecordName($class)
  1384. );
  1385. }
  1386. $this->loadFromResult($result, TRUE);
  1387. return $this;
  1388. }
  1389. /**
  1390. * Loads a record from the database directly from a result object
  1391. *
  1392. * @param Iterator $result The result object to use for loading the current object
  1393. * @param boolean $ignore_identity_map If the identity map should be ignored and the values loaded no matter what
  1394. * @return boolean If the record was loaded from the identity map
  1395. */
  1396. protected function loadFromResult($result, $ignore_identity_map=FALSE)
  1397. {
  1398. $class = get_class($this);
  1399. $table = fORM::tablize($class);
  1400. $row = $result->current();
  1401. $db = fORMDatabase::retrieve();
  1402. if (!isset(self::$unescape_map[$class])) {
  1403. self::$unescape_map[$class] = array();
  1404. $column_info = fORMSchema::retrieve()->getColumnInfo($table);
  1405. foreach ($column_info as $column => $info) {
  1406. if (in_array($info['type'], array('blob', 'boolean', 'date', 'time', 'timestamp'))) {
  1407. self::$unescape_map[$class][$column] = $info['type'];
  1408. }
  1409. }
  1410. }
  1411. $pk_columns = fORMSchema::retrieve()->getKeys($table, 'primary');
  1412. foreach ($pk_columns as $column) {
  1413. $value = $row[$column];
  1414. if ($value !== NULL && isset(self::$unescape_map[$class][$column])) {
  1415. $value = $db->unescape(self::$unescape_map[$class][$column], $value);
  1416. }
  1417. $this->values[$column] = fORM::objectify($class, $column, $value);
  1418. unset($row[$column]);
  1419. }
  1420. $hash = self::hash($this->values, $class);
  1421. if (!$ignore_identity_map && $this->loadFromIdentityMap($this->values, $hash)) {
  1422. return TRUE;
  1423. }
  1424. foreach ($row as $column => $value) {
  1425. if ($value !== NULL && isset(self::$unescape_map[$class][$column])) {
  1426. $value = $db->unescape(self::$unescape_map[$class][$column], $value);
  1427. }
  1428. $this->values[$column] = fORM::objectify($class, $column, $value);
  1429. }
  1430. // Save this object to the identity map
  1431. if (!isset(self::$identity_map[$class])) {
  1432. self::$identity_map[$class] = array();
  1433. }
  1434. self::$identity_map[$class][$hash] = $this;
  1435. fORM::callHookCallbacks(
  1436. $this,
  1437. 'post::loadFromResult()',
  1438. $this->values,
  1439. $this->old_values,
  1440. $this->related_records,
  1441. $this->cache
  1442. );
  1443. return FALSE;
  1444. }
  1445. /**
  1446. * Tries to load the object (via references to class vars) from the fORM identity map
  1447. *
  1448. * @param array $row The data source for the primary key values
  1449. * @param string $hash The unique hash for this record
  1450. * @return boolean If the load was successful
  1451. */
  1452. protected function loadFromIdentityMap($row, $hash)
  1453. {
  1454. $class = get_class($this);
  1455. if (!isset(self::$identity_map[$class])) {
  1456. return FALSE;
  1457. }
  1458. if (!isset(self::$identity_map[$class][$hash])) {
  1459. return FALSE;
  1460. }
  1461. $object = self::$identity_map[$class][$hash];
  1462. // If we got a result back, it is the object we are creating
  1463. $this->cache = &$object->cache;
  1464. $this->values = &$object->values;
  1465. $this->old_values = &$object->old_values;
  1466. $this->related_records = &$object->related_records;
  1467. return TRUE;
  1468. }
  1469. /**
  1470. * Sets the values for this record by getting values from the request through the fRequest class
  1471. *
  1472. * @return fActiveRecord The record object, to allow for method chaining
  1473. */
  1474. public function populate()
  1475. {
  1476. $class = get_class($this);
  1477. if (fORM::getActiveRecordMethod($class, 'populate')) {
  1478. return $this->__call('populate', array());
  1479. }
  1480. fORM::callHookCallbacks(
  1481. $this,
  1482. 'pre::populate()',
  1483. $this->values,
  1484. $this->old_values,
  1485. $this->related_records,
  1486. $this->cache
  1487. );
  1488. $table = fORM::tablize($class);
  1489. $column_info = fORMSchema::retrieve()->getColumnInfo($table);
  1490. foreach ($column_info as $column => $info) {
  1491. if (fRequest::check($column)) {
  1492. $method = 'set' . fGrammar::camelize($column, TRUE);
  1493. $this->$method(fRequest::get($column));
  1494. }
  1495. }
  1496. fORM::callHookCallbacks(
  1497. $this,
  1498. 'post::populate()',
  1499. $this->values,
  1500. $this->old_values,
  1501. $this->related_records,
  1502. $this->cache
  1503. );
  1504. return $this;
  1505. }
  1506. /**
  1507. * Retrieves a value from the record and prepares it for output into html.
  1508. *
  1509. * Below are the transformations performed:
  1510. *
  1511. * - **varchar, char, text**: will run through fHTML::prepare(), if `TRUE` is passed the text will be run through fHTML::convertNewLinks() and fHTML::makeLinks()
  1512. * - **boolean**: will return `'Yes'` or `'No'`
  1513. * - **integer**: will add thousands/millions/etc. separators
  1514. * - **float**: will add thousands/millions/etc. separators and takes 1 parameter to specify the number of decimal places
  1515. * - **date, time, timestamp**: `format()` will be called on the fDate/fTime/fTimestamp object with the 1 parameter specified
  1516. * - **objects**: the object will be converted to a string by `__toString()` or a `(string)` cast and then will be run through fHTML::prepare()
  1517. *
  1518. * @param string $column The name of the column to retrieve
  1519. * @param mixed $formatting The formatting parameter, if applicable
  1520. * @return string The formatted value for the column specified
  1521. */
  1522. protected function prepare($column, $formatting=NULL)
  1523. {
  1524. if (!array_key_exists($column, $this->values)) {
  1525. throw new fProgrammerException(
  1526. 'The column specified, %s, does not exist',
  1527. $column
  1528. );
  1529. }
  1530. $column_info = fORMSchema::retrieve()->getColumnInfo(fORM::tablize(get_class($this)), $column);
  1531. $column_type = $column_info['type'];
  1532. // Ensure the programmer is calling the function properly
  1533. if ($column_type == 'blob') {
  1534. throw new fProgrammerException(
  1535. 'The column specified, %s, can not be prepared because it is a blob column',
  1536. $column
  1537. );
  1538. }
  1539. if ($formatting !== NULL && in_array($column_type, array('integer', 'boolean'))) {
  1540. throw new fProgrammerException(
  1541. 'The column specified, %s, does not support any formatting options',
  1542. $column
  1543. );
  1544. }
  1545. // Grab the value for empty value checking
  1546. $method_name = 'get' . fGrammar::camelize($column, TRUE);
  1547. $value = $this->$method_name();
  1548. // Date/time objects
  1549. if (is_object($value) && in_array($column_type, array('date', 'time', 'timestamp'))) {
  1550. if ($formatting === NULL) {
  1551. throw new fProgrammerException(
  1552. 'The column specified, %s, requires one formatting parameter, a valid date() formatting string',
  1553. $column
  1554. );
  1555. }
  1556. return $value->format($formatting);
  1557. }
  1558. // Other objects
  1559. if (is_object($value) && is_callable(array($value, '__toString'))) {
  1560. $value = $value->__toString();
  1561. } elseif (is_object($value)) {
  1562. $value = (string) $value;
  1563. }
  1564. // Ensure the value matches the data type specified to prevent mangling
  1565. if ($column_type == 'boolean' && is_bool($value)) {
  1566. return ($value) ? 'Yes' : 'No';
  1567. }
  1568. if ($column_type == 'integer' && is_numeric($value)) {
  1569. return number_format($value, 0, '', ',');
  1570. }
  1571. if ($column_type == 'float' && is_numeric($value)) {
  1572. // If the user passed in a formatting value, use it
  1573. if ($formatting !== NULL && is_numeric($formatting)) {
  1574. $decimal_places = (int) $formatting;
  1575. // If the column has a pre-defined number of decimal places, use that
  1576. } elseif ($column_info['decimal_places'] !== NULL) {
  1577. $decimal_places = $column_info['decimal_places'];
  1578. // This figures out how many decimal places are part of the current value
  1579. } else {
  1580. $value_parts = explode('.', $value);
  1581. $decimal_places = (!isset($value_parts[1])) ? 0 : strlen($value_parts[1]);
  1582. }
  1583. return number_format($value, $decimal_places, '.', ',');
  1584. }
  1585. // Turn line-breaks into breaks for text fields and add links
  1586. if ($formatting === TRUE && in_array($column_type, array('varchar', 'char', 'text'))) {
  1587. return fHTML::makeLinks(fHTML::convertNewlines(fHTML::prepare($value)));
  1588. }
  1589. // Anything that has gotten to here is a string value, or is not the
  1590. // proper data type for the column, so we just make sure it is marked
  1591. // up properly for display in HTML
  1592. return fHTML::prepare($value);
  1593. }
  1594. /**
  1595. * Generates a pre-formatted block of text containing the method signatures for all methods (including dynamic ones)
  1596. *
  1597. * @param boolean $include_doc_comments If the doc block comments for each method should be included
  1598. * @return string A preformatted block of text with the method signatures and optionally the doc comment
  1599. */
  1600. public function reflect($include_doc_comments=FALSE)
  1601. {
  1602. $signatures = array();
  1603. $class = get_class($this);
  1604. $columns_info = fORMSchema::retrieve()->getColumnInfo(fORM::tablize($class));
  1605. foreach ($columns_info as $column => $column_info) {
  1606. $camelized_column = fGrammar::camelize($column, TRUE);
  1607. // Get and set methods
  1608. $signature = '';
  1609. if ($include_doc_comments) {
  1610. $fixed_type = $column_info['type'];
  1611. if ($fixed_type == 'blob') {
  1612. $fixed_type = 'string';
  1613. }
  1614. if ($fixed_type == 'date') {
  1615. $fixed_type = 'fDate';
  1616. }
  1617. if ($fixed_type == 'timestamp') {
  1618. $fixed_type = 'fTimestamp';
  1619. }
  1620. if ($fixed_type == 'time') {
  1621. $fixed_type = 'fTime';
  1622. }
  1623. $signature .= "/**\n";
  1624. $signature .= " * Gets the current value of " . $column . "\n";
  1625. $signature .= " * \n";
  1626. $signature .= " * @return " . $fixed_type . " The current value\n";
  1627. $signature .= " */\n";
  1628. }
  1629. $get_method = 'get' . $camelized_column;
  1630. $signature .= 'public function ' . $get_method . '()';
  1631. $signatures[$get_method] = $signature;
  1632. $signature = '';
  1633. if ($include_doc_comments) {
  1634. $fixed_type = $column_info['type'];
  1635. if ($fixed_type == 'blob') {
  1636. $fixed_type = 'string';
  1637. }
  1638. if ($fixed_type == 'date') {
  1639. $fixed_type = 'fDate|string';
  1640. }
  1641. if ($fixed_type == 'timestamp') {
  1642. $fixed_type = 'fTimestamp|string';
  1643. }
  1644. if ($fixed_type == 'time') {
  1645. $fixed_type = 'fTime|string';
  1646. }
  1647. $signature .= "/**\n";
  1648. $signature .= " * Sets the value for " . $column . "\n";
  1649. $signature .= " * \n";
  1650. $signature .= " * @param " . $fixed_type . " \$" . $column . " The new value\n";
  1651. $signature .= " * @return void\n";
  1652. $signature .= " */\n";
  1653. }
  1654. $set_method = 'set' . $camelized_column;
  1655. $signature .= 'public function ' . $set_method . '($' . $column . ')';
  1656. $signatures[$set_method] = $signature;
  1657. // The encode method
  1658. $signature = '';
  1659. if ($include_doc_comments) {
  1660. $signature .= "/**\n";
  1661. $signature .= " * Encodes the value of " . $column . " for output into an HTML form\n";
  1662. $signature .= " * \n";
  1663. if (in_array($column_info['type'], array('time', 'timestamp', 'date'))) {
  1664. $signature .= " * @param string \$date_formatting_string A date() compatible formatting string\n";
  1665. }
  1666. if (in_array($column_info['type'], array('float'))) {
  1667. $signature .= " * @param integer \$decimal_places The number of decimal places to include - if not specified will default to the precision of the column or the current value\n";
  1668. }
  1669. $signature .= " * @return string The HTML form-ready value\n";
  1670. $signature .= " */\n";
  1671. }
  1672. $encode_method = 'encode' . $camelized_column;
  1673. $signature .= 'public function ' . $encode_method . '(';
  1674. if (in_array($column_info['type'], array('time', 'timestamp', 'date'))) {
  1675. $signature .= '$date_formatting_string';
  1676. }
  1677. if (in_array($column_info['type'], array('float'))) {
  1678. $signature .= '$decimal_places=NULL';
  1679. }
  1680. $signature .= ')';
  1681. $signatures[$encode_method] = $signature;
  1682. // The prepare method
  1683. $signature = '';
  1684. if ($include_doc_comments) {
  1685. $signature .= "/**\n";
  1686. $signature .= " * Prepares the value of " . $column . " for output into HTML\n";
  1687. $signature .= " * \n";
  1688. if (in_array($column_info['type'], array('time', 'timestamp', 'date'))) {
  1689. $signature .= " * @param string \$date_formatting_string A date() compatible formatting string\n";
  1690. }
  1691. if (in_array($column_info['type'], array('float'))) {
  1692. $signature .= " * @param integer \$decimal_places The number of decimal places to include - if not specified will default to the precision of the column or the current value\n";
  1693. }
  1694. if (in_array($column_info['type'], array('varchar', 'char', 'text'))) {
  1695. $signature .= " * @param boolean \$create_links_and_line_breaks Will cause links to be automatically converted into [a] tags and line breaks into [br] tags \n";
  1696. }
  1697. $signature .= " * @return string The HTML-ready value\n";
  1698. $signature .= " */\n";
  1699. }
  1700. $prepare_method = 'prepare' . $camelized_column;
  1701. $signature .= 'public function ' . $prepare_method . '(';
  1702. if (in_array($column_info['type'], array('time', 'timestamp', 'date'))) {
  1703. $signature .= '$date_formatting_string';
  1704. }
  1705. if (in_array($column_info['type'], array('float'))) {
  1706. $signature .= '$decimal_places=NULL';
  1707. }
  1708. if (in_array($column_info['type'], array('varchar', 'char', 'text'))) {
  1709. $signature .= '$create_links_and_line_breaks=FALSE';
  1710. }
  1711. $signature .= ')';
  1712. $signatures[$prepare_method] = $signature;
  1713. // The inspect method
  1714. $signature = '';
  1715. if ($include_doc_comments) {
  1716. $signature .= "/**\n";
  1717. $signature .= " * Returns metadata about " . $column . "\n";
  1718. $signature .= " * \n";
  1719. $elements = array('type', 'not_null', 'default');
  1720. if (in_array($column_info['type'], array('varchar', 'char', 'text'))) {
  1721. $elements[] = 'valid_values';
  1722. $elements[] = 'max_length';
  1723. }
  1724. if ($column_info['type'] == 'float') {
  1725. $elements[] = 'decimal_places';
  1726. }
  1727. if ($column_info['type'] == 'integer') {
  1728. $elements[] = 'auto_increment';
  1729. }
  1730. $signature .= " * @param string \$element The element to return. Must be one of: '" . join("', '", $elements) . "'.\n";
  1731. $signature .= " * @return mixed The metadata array or a single element\n";
  1732. $signature .= " */\n";
  1733. }
  1734. $inspect_method = 'inspect' . $camelized_column;
  1735. $signature .= 'public function ' . $inspect_method . '($element=NULL)';
  1736. $signatures[$inspect_method] = $signature;
  1737. }
  1738. fORMRelated::reflect($class, $signatures, $include_doc_comments);
  1739. fORM::callReflectCallbacks($class, $signatures, $include_doc_comments);
  1740. $reflection = new ReflectionClass($class);
  1741. $methods = $reflection->getMethods();
  1742. foreach ($methods as $method) {
  1743. $signature = '';
  1744. if (!$method->isPublic() || $method->getName() == '__call') {
  1745. continue;
  1746. }
  1747. if ($method->isFinal()) {
  1748. $signature .= 'final ';
  1749. }
  1750. if ($method->isAbstract()) {
  1751. $signature .= 'abstract ';
  1752. }
  1753. if ($method->isStatic()) {
  1754. $signature .= 'static ';
  1755. }
  1756. $signature .= 'public function ';
  1757. if ($method->returnsReference()) {
  1758. $signature .= '&';
  1759. }
  1760. $signature .= $method->getName();
  1761. $signature .= '(';
  1762. $parameters = $method->getParameters();
  1763. foreach ($parameters as $parameter) {
  1764. if (substr($signature, -1) == '(') {
  1765. $signature .= '';
  1766. } else {
  1767. $signature .= ', ';
  1768. }
  1769. if ($parameter->isArray()) {
  1770. $signature .= 'array ';
  1771. }
  1772. if ($parameter->getClass()) {
  1773. $signature .= $parameter->getClass()->getName() . ' ';
  1774. }
  1775. if ($parameter->isPassedByReference()) {
  1776. $signature .= '&';
  1777. }
  1778. $signature .= '$' . $parameter->getName();
  1779. if ($parameter->isDefaultValueAvailable()) {
  1780. $val = var_export($parameter->getDefaultValue(), TRUE);
  1781. if ($val == 'true') {
  1782. $val = 'TRUE';
  1783. }
  1784. if ($val == 'false') {
  1785. $val = 'FALSE';
  1786. }
  1787. if (is_array($parameter->getDefaultValue())) {
  1788. $val = preg_replace('#array\s+\(\s+#', 'array(', $val);
  1789. $val = preg_replace('#,(\r)?\n #', ', ', $val);
  1790. $val = preg_replace('#,(\r)?\n\)#', ')', $val);
  1791. }
  1792. $signature .= '=' . $val;
  1793. }
  1794. }
  1795. $signature .= ')';
  1796. if ($include_doc_comments) {
  1797. $comment = $method->getDocComment();
  1798. $comment = preg_replace('#^\t+#m', '', $comment);
  1799. $signature = $comment . "\n" . $signature;
  1800. }
  1801. $signatures[$method->getName()] = $signature;
  1802. }
  1803. ksort($signatures);
  1804. return join("\n\n", $signatures);
  1805. }
  1806. /**
  1807. * Generates a clone of the current record, removing any auto incremented primary key value and allowing for replicating related records
  1808. *
  1809. * This method will accept three different sets of parameters:
  1810. *
  1811. * - No parameters: this object will be cloned
  1812. * - A single `TRUE` value: this object plus all many-to-many associations and all child records (recursively) will be cloned
  1813. * - Any number of plural related record class names: the many-to-many associations or child records that correspond to the classes specified will be cloned
  1814. *
  1815. * The class names specified can be a simple class name if there is only a
  1816. * single route between the two corresponding database tables. If there is
  1817. * more than one route between the two tables, the class name should be
  1818. * substituted with a string in the format `'RelatedClass{route}'`.
  1819. *
  1820. * @param string $related_class The plural related class to replicate - see method description for details
  1821. * @param string ...
  1822. * @return fActiveRecord The cloned record
  1823. */
  1824. public function replicate($related_class=NULL)
  1825. {
  1826. fActiveRecord::$replicate_level++;
  1827. $class = get_class($this);
  1828. $hash = self::hash($this->values, $class);
  1829. $table = fORM::tablize($class);
  1830. // If the object has not been replicated yet, do it now
  1831. if (!isset(fActiveRecord::$replicate_map[$class])) {
  1832. fActiveRecord::$replicate_map[$class] = array();
  1833. }
  1834. if (!isset(fActiveRecord::$replicate_map[$class][$hash])) {
  1835. fActiveRecord::$replicate_map[$class][$hash] = clone $this;
  1836. // We need the primary key to get a hash, otherwise certain recursive relationships end up losing members
  1837. $pk_columns = fORMSchema::retrieve()->getKeys($table, 'primary');
  1838. if (sizeof($pk_columns) == 1 && fORMSchema::retrieve()->getColumnInfo($table, $pk_columns[0], 'auto_increment')) {
  1839. fActiveRecord::$replicate_map[$class][$hash]->values[$pk_columns[0]] = $this->values[$pk_columns[0]];
  1840. }
  1841. }
  1842. $clone = fActiveRecord::$replicate_map[$class][$hash];
  1843. $parameters = func_get_args();
  1844. $recursive = FALSE;
  1845. $many_to_many_relationships = fORMSchema::retrieve()->getRelationships($table, 'many-to-many');
  1846. $one_to_many_relationships = fORMSchema::retrieve()->getRelationships($table, 'one-to-many');
  1847. // When just TRUE is passed we recursively replicate all related records
  1848. if (sizeof($parameters) == 1 && $parameters[0] === TRUE) {
  1849. $parameters = array();
  1850. $recursive = TRUE;
  1851. foreach ($many_to_many_relationships as $relationship) {
  1852. $parameters[] = fGrammar::pluralize(fORM::classize($relationship['related_table'])) . '{' . $relationship['join_table'] . '}';
  1853. }
  1854. foreach ($one_to_many_relationships as $relationship) {
  1855. $parameters[] = fGrammar::pluralize(fORM::classize($relationship['related_table'])) . '{' . $relationship['related_column'] . '}';
  1856. }
  1857. }
  1858. $record_sets = array();
  1859. foreach ($parameters as $parameter) {
  1860. // Parse the Class{route} strings
  1861. if (strpos($parameter, '{') !== FALSE) {
  1862. $brace = strpos($parameter, '{');
  1863. $related_class = fGrammar::singularize(substr($parameter, 0, $brace));
  1864. $related_table = fORM::tablize($related_class);
  1865. $route = substr($parameter, $brace+1, -1);
  1866. } else {
  1867. $related_class = fGrammar::singularize($parameter);
  1868. $related_table = fORM::tablize($related_class);
  1869. $route = fORMSchema::getRouteName($table, $related_table);
  1870. }
  1871. // Determine the kind of relationship
  1872. $many_to_many = FALSE;
  1873. $one_to_many = FALSE;
  1874. foreach ($many_to_many_relationships as $relationship) {
  1875. if ($relationship['related_table'] == $related_table && $relationship['join_table'] == $route) {
  1876. $many_to_many = TRUE;
  1877. break;
  1878. }
  1879. }
  1880. foreach ($one_to_many_relationships as $relationship) {
  1881. if ($relationship['related_table'] == $related_table && $relationship['related_column'] == $route) {
  1882. $one_to_many = TRUE;
  1883. break;
  1884. }
  1885. }
  1886. if (!$many_to_many && !$one_to_many) {
  1887. throw new fProgrammerException(
  1888. 'The related class specified, %1$s, does not appear to be in a many-to-many or one-to-many relationship with %$2s',
  1889. $parameter,
  1890. get_class($this)
  1891. );
  1892. }
  1893. // Get the related records
  1894. $record_set = fORMRelated::buildRecords($class, $this->values, $this->related_records, $related_class, $route);
  1895. // One-to-many records need to be replicated, possibly recursively
  1896. if ($one_to_many) {
  1897. if ($recursive) {
  1898. $records = $record_set->call('replicate', TRUE);
  1899. } else {
  1900. $records = $record_set->call('replicate');
  1901. }
  1902. $record_set = fRecordSet::buildFromArray($related_class, $records);
  1903. $record_set->call(
  1904. 'set' . fGrammar::camelize($route, TRUE),
  1905. NULL
  1906. );
  1907. }
  1908. // Cause the related records to be associated with the new clone
  1909. fORMRelated::associateRecords($class, $clone->related_records, $related_class, $record_set, $route);
  1910. }
  1911. fActiveRecord::$replicate_level--;
  1912. if (!fActiveRecord::$replicate_level) {
  1913. // This removes the primary keys we had added back in for proper duplicate detection
  1914. foreach (fActiveRecord::$replicate_map as $class => $records) {
  1915. $table = fORM::tablize($class);
  1916. $pk_columns = fORMSchema::retrieve()->getKeys($table, 'primary');
  1917. if (sizeof($pk_columns) != 1 || !fORMSchema::retrieve()->getColumnInfo($table, $pk_columns[0], 'auto_increment')) {
  1918. continue;
  1919. }
  1920. foreach ($records as $hash => $record) {
  1921. $record->values[$pk_columns[0]] = NULL;
  1922. }
  1923. }
  1924. fActiveRecord::$replicate_map = array();
  1925. }
  1926. return $clone;
  1927. }
  1928. /**
  1929. * Sets a value to the record
  1930. *
  1931. * @param string $column The column to set the value to
  1932. * @param mixed $value The value to set
  1933. * @return fActiveRecord This record, to allow for method chaining
  1934. */
  1935. protected function set($column, $value)
  1936. {
  1937. if (!array_key_exists($column, $this->values)) {
  1938. throw new fProgrammerException(
  1939. 'The column specified, %s, does not exist',
  1940. $column
  1941. );
  1942. }
  1943. // We consider an empty string to be equivalent to NULL
  1944. if ($value === '') {
  1945. $value = NULL;
  1946. }
  1947. $class = get_class($this);
  1948. $value = fORM::objectify($class, $column, $value);
  1949. // Float and int columns that look like numbers with commas will have the commas removed
  1950. if (is_string($value)) {
  1951. $table = fORM::tablize($class);
  1952. $type = fORMSchema::retrieve()->getColumnInfo($table, $column, 'type');
  1953. if (in_array($type, array('integer', 'float')) && preg_match('#^(\d+,)+\d+(\.\d+)?$#', $value)) {
  1954. $value = str_replace(',', '', $value);
  1955. }
  1956. }
  1957. self::assign($this->values, $this->old_values, $column, $value);
  1958. return $this;
  1959. }
  1960. /**
  1961. * Stores a record in the database, whether existing or new
  1962. *
  1963. * This method will start database and filesystem transactions if they have
  1964. * not already been started.
  1965. *
  1966. * @throws fValidationException When ::validate() throws an exception
  1967. *
  1968. * @return fActiveRecord The record object, to allow for method chaining
  1969. */
  1970. public function store()
  1971. {
  1972. $class = get_class($this);
  1973. if (fORM::getActiveRecordMethod($class, 'store')) {
  1974. return $this->__call('store', array());
  1975. }
  1976. fORM::callHookCallbacks(
  1977. $this,
  1978. 'pre::store()',
  1979. $this->values,
  1980. $this->old_values,
  1981. $this->related_records,
  1982. $this->cache
  1983. );
  1984. try {
  1985. $table = fORM::tablize($class);
  1986. $column_info = fORMSchema::retrieve()->getColumnInfo($table);
  1987. // New auto-incrementing records require lots of special stuff, so we'll detect them here
  1988. $new_autoincrementing_record = FALSE;
  1989. if (!$this->exists()) {
  1990. $pk_columns = fORMSchema::retrieve()->getKeys($table, 'primary');
  1991. if (sizeof($pk_columns) == 1 && $column_info[$pk_columns[0]]['auto_increment'] && !$this->values[$pk_columns[0]]) {
  1992. $new_autoincrementing_record = TRUE;
  1993. $pk_column = $pk_columns[0];
  1994. }
  1995. }
  1996. $inside_db_transaction = fORMDatabase::retrieve()->isInsideTransaction();
  1997. if (!$inside_db_transaction) {
  1998. fORMDatabase::retrieve()->translatedQuery('BEGIN');
  1999. }
  2000. fORM::callHookCallbacks(
  2001. $this,
  2002. 'post-begin::store()',
  2003. $this->values,
  2004. $this->old_values,
  2005. $this->related_records,
  2006. $this->cache
  2007. );
  2008. $this->validate();
  2009. fORM::callHookCallbacks(
  2010. $this,
  2011. 'post-validate::store()',
  2012. $this->values,
  2013. $this->old_values,
  2014. $this->related_records,
  2015. $this->cache
  2016. );
  2017. // Storing main table
  2018. $sql_values = array();
  2019. foreach ($column_info as $column => $info) {
  2020. $value = fORM::scalarize($class, $column, $this->values[$column]);
  2021. $sql_values[$column] = fORMDatabase::escapeBySchema($table, $column, $value);
  2022. }
  2023. // Most databases don't like the auto incrementing primary key to be set to NULL
  2024. if ($new_autoincrementing_record && $sql_values[$pk_column] == 'NULL') {
  2025. unset($sql_values[$pk_column]);
  2026. }
  2027. if (!$this->exists()) {
  2028. $sql = $this->constructInsertSQL($sql_values);
  2029. } else {
  2030. $sql = $this->constructUpdateSQL($sql_values);
  2031. }
  2032. $result = fORMDatabase::retrieve()->translatedQuery($sql);
  2033. // If there is an auto-incrementing primary key, grab the value from the database
  2034. if ($new_autoincrementing_record) {
  2035. $this->set($pk_column, $result->getAutoIncrementedValue());
  2036. }
  2037. // Storing *-to-many relationships
  2038. fORMRelated::store($class, $this->values, $this->related_records);
  2039. fORM::callHookCallbacks(
  2040. $this,
  2041. 'pre-commit::store()',
  2042. $this->values,
  2043. $this->old_values,
  2044. $this->related_records,
  2045. $this->cache
  2046. );
  2047. if (!$inside_db_transaction) {
  2048. fORMDatabase::retrieve()->translatedQuery('COMMIT');
  2049. }
  2050. fORM::callHookCallbacks(
  2051. $this,
  2052. 'post-commit::store()',
  2053. $this->values,
  2054. $this->old_values,
  2055. $this->related_records,
  2056. $this->cache
  2057. );
  2058. } catch (fException $e) {
  2059. if (!$inside_db_transaction) {
  2060. fORMDatabase::retrieve()->translatedQuery('ROLLBACK');
  2061. }
  2062. fORM::callHookCallbacks(
  2063. $this,
  2064. 'post-rollback::store()',
  2065. $this->values,
  2066. $this->old_values,
  2067. $this->related_records,
  2068. $this->cache
  2069. );
  2070. if ($new_autoincrementing_record && self::hasOld($this->old_values, $pk_column)) {
  2071. $this->values[$pk_column] = self::retrieveOld($this->old_values, $pk_column);
  2072. unset($this->old_values[$pk_column]);
  2073. }
  2074. throw $e;
  2075. }
  2076. fORM::callHookCallbacks(
  2077. $this,
  2078. 'post::store()',
  2079. $this->values,
  2080. $this->old_values,
  2081. $this->related_records,
  2082. $this->cache
  2083. );
  2084. $was_new = !$this->exists();
  2085. // If we got here we succefully stored, so update old values to make exists() work
  2086. foreach ($this->values as $column => $value) {
  2087. $this->old_values[$column] = array($value);
  2088. }
  2089. // If the object was just inserted into the database, save it to the identity map
  2090. if ($was_new) {
  2091. $hash = self::hash($this->values, $class);
  2092. if (!isset(self::$identity_map[$class])) {
  2093. self::$identity_map[$class] = array();
  2094. }
  2095. self::$identity_map[$class][$hash] = $this;
  2096. }
  2097. return $this;
  2098. }
  2099. /**
  2100. * Validates the values of the record against the database and any additional validation rules
  2101. *
  2102. * @throws fValidationException When the record, or one of the associated records, violates one of the validation rules for the class or can not be properly stored in the database
  2103. *
  2104. * @param boolean $return_messages If an array of validation messages should be returned instead of an exception being thrown
  2105. * @return void|array If $return_messages is TRUE, an array of validation messages will be returned
  2106. */
  2107. public function validate($return_messages=FALSE)
  2108. {
  2109. $class = get_class($this);
  2110. if (fORM::getActiveRecordMethod($class, 'validate')) {
  2111. return $this->__call('validate', array($return_messages));
  2112. }
  2113. $validation_messages = array();
  2114. fORM::callHookCallbacks(
  2115. $this,
  2116. 'pre::validate()',
  2117. $this->values,
  2118. $this->old_values,
  2119. $this->related_records,
  2120. $this->cache,
  2121. $validation_messages
  2122. );
  2123. // Validate the local values
  2124. $local_validation_messages = fORMValidation::validate($this, $this->values, $this->old_values);
  2125. // Validate related records
  2126. $related_validation_messages = fORMValidation::validateRelated($this, $this->values, $this->related_records);
  2127. $validation_messages = array_merge($validation_messages, $local_validation_messages, $related_validation_messages);
  2128. fORM::callHookCallbacks(
  2129. $this,
  2130. 'post::validate()',
  2131. $this->values,
  2132. $this->old_values,
  2133. $this->related_records,
  2134. $this->cache,
  2135. $validation_messages
  2136. );
  2137. $validation_messages = array_unique($validation_messages);
  2138. $validation_messages = fORMValidation::replaceMessages($class, $validation_messages);
  2139. $validation_messages = fORMValidation::reorderMessages($class, $validation_messages);
  2140. if ($return_messages) {
  2141. return $validation_messages;
  2142. }
  2143. if (!empty($validation_messages)) {
  2144. throw new fValidationException(
  2145. 'The following problems were found:',
  2146. $validation_messages
  2147. );
  2148. }
  2149. }
  2150. }
  2151. /**
  2152. * Copyright (c) 2007-2009 Will Bond <will@flourishlib.com>, others
  2153. *
  2154. * Permission is hereby granted, free of charge, to any person obtaining a copy
  2155. * of this software and associated documentation files (the "Software"), to deal
  2156. * in the Software without restriction, including without limitation the rights
  2157. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  2158. * copies of the Software, and to permit persons to whom the Software is
  2159. * furnished to do so, subject to the following conditions:
  2160. *
  2161. * The above copyright notice and this permission notice shall be included in
  2162. * all copies or substantial portions of the Software.
  2163. *
  2164. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2165. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2166. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  2167. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  2168. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  2169. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  2170. * THE SOFTWARE.
  2171. */