PageRenderTime 57ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/classphp/flourish/fActiveRecord.php

https://github.com/jsuarez/Lexer
PHP | 2603 lines | 1584 code | 428 blank | 591 comment | 365 complexity | d1c640ab2b1ebdece3e32da01731f6a2 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-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 t…

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