/classphp/flourish/fActiveRecord.php
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
- <?php
- /**
- * An [http://en.wikipedia.org/wiki/Active_record_pattern active record pattern] base class
- *
- * This class uses fORMSchema to inspect your database and provides an
- * OO interface to a single database table. The class dynamically handles
- * method calls for getting, setting and other operations on columns. It also
- * dynamically handles retrieving and storing related records.
- *
- * @copyright Copyright (c) 2007-2009 Will Bond, others
- * @author Will Bond [wb] <will@flourishlib.com>
- * @author Will Bond, iMarc LLC [wb-imarc] <will@imarc.net>
- * @license http://flourishlib.com/license
- *
- * @package Flourish
- * @link http://flourishlib.com/fActiveRecord
- *
- * @version 1.0.0b45
- * @changes 1.0.0b45 Added support for `!~`, `&~`, `><` and OR comparisons to ::checkConditions(), made object handling in ::checkConditions() more robust [wb, 2009-09-21]
- * @changes 1.0.0b44 Updated code for new fValidationException API [wb, 2009-09-18]
- * @changes 1.0.0b43 Updated code for new fRecordSet API [wb, 2009-09-16]
- * @changes 1.0.0b42 Corrected a grammar bug in ::hash() [wb, 2009-09-09]
- * @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]
- * @changes 1.0.0b40 Added a check to the configuration part of ::__construct() to ensure modelled tables have primary keys [wb, 2009-08-26]
- * @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]
- * @changes 1.0.0b38 Updated ::changed() to do a strict comparison when at least one value is NULL [wb, 2009-08-17]
- * @changes 1.0.0b37 Changed ::__construct() to allow any Iterator object instead of just fResult [wb, 2009-08-12]
- * @changes 1.0.0b36 Fixed a bug with setting NULL values from v1.0.0b33 [wb, 2009-08-10]
- * @changes 1.0.0b35 Fixed a bug with unescaping data in ::loadFromResult() from v1.0.0b33 [wb, 2009-08-10]
- * @changes 1.0.0b34 Added the ability to compare fActiveRecord objects in ::checkConditions() [wb, 2009-08-07]
- * @changes 1.0.0b33 Performance enhancements to ::__call() and ::__construct() [wb, 2009-08-07]
- * @changes 1.0.0b32 Changed ::delete() to remove auto-incrementing primary keys after the post::delete() hook [wb, 2009-07-29]
- * @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]
- * @changes 1.0.0b30 Updated ::reflect() for new fORM::callReflectCallbacks() API [wb, 2009-07-13]
- * @changes 1.0.0b29 Updated to use new fORM::callInspectCallbacks() method [wb, 2009-07-13]
- * @changes 1.0.0b28 Fixed a bug where records would break the identity map at the end of ::store() [wb, 2009-07-09]
- * @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]
- * @changes 1.0.0b26 Added ::checkConditions() from fRecordSet [wb, 2009-07-08]
- * @changes 1.0.0b25 Updated ::validate() to use new fORMValidation API, including new message search/replace functionality [wb, 2009-07-01]
- * @changes 1.0.0b24 Changed ::validate() to remove duplicate validation messages [wb, 2009-06-30]
- * @changes 1.0.0b23 Updated code for new fORMValidation::validateRelated() API [wb, 2009-06-26]
- * @changes 1.0.0b22 Added support for the $formatting parameter to encode methods on char, text and varchar columns [wb, 2009-06-19]
- * @changes 1.0.0b21 Performance tweaks and updates for fORM and fORMRelated API changes [wb, 2009-06-15]
- * @changes 1.0.0b20 Changed replacement values in preg_replace() calls to be properly escaped [wb, 2009-06-11]
- * @changes 1.0.0b19 Added `list{RelatedRecords}()` methods, updated code for new fORMRelated API [wb, 2009-06-02]
- * @changes 1.0.0b18 Changed ::store() to use new fORMRelated::store() method [wb, 2009-06-02]
- * @changes 1.0.0b17 Added some missing parameter information to ::reflect() [wb, 2009-06-01]
- * @changes 1.0.0b16 Fixed bugs in ::__clone() and ::replicate() related to recursive relationships [wb-imarc, 2009-05-20]
- * @changes 1.0.0b15 Fixed an incorrect variable reference in ::store() [wb, 2009-05-06]
- * @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]
- * @changes 1.0.0b13 ::delete(), ::load(), ::populate() and ::store() now return the record to allow for method chaining [wb, 2009-03-23]
- * @changes 1.0.0b12 ::set() now removes commas from integers and floats to prevent validation issues [wb, 2009-03-22]
- * @changes 1.0.0b11 ::encode() no longer adds commas to floats [wb, 2009-03-22]
- * @changes 1.0.0b10 ::__wakeup() no longer registers the record as the definitive copy in the identity map [wb, 2009-03-22]
- * @changes 1.0.0b9 Changed ::__construct() to populate database default values when a non-existing record is instantiated [wb, 2009-01-12]
- * @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]
- * @changes 1.0.0b7 Fixed ::__construct() to not trigger the post::__construct() hook when force-configured [wb, 2008-12-30]
- * @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]
- * @changes 1.0.0b5 Fixed ::replicate() to use plural record names for related records [wb, 2008-12-12]
- * @changes 1.0.0b4 Added ::replicate() to allow cloning along with related records [wb, 2008-12-12]
- * @changes 1.0.0b3 Changed ::__clone() to clone objects contains in the values and cache arrays [wb, 2008-12-11]
- * @changes 1.0.0b2 Added the ::__clone() method to properly duplicate a record [wb, 2008-12-04]
- * @changes 1.0.0b The initial implementation [wb, 2007-08-04]
- */
- abstract class fActiveRecord
- {
- // The following constants allow for nice looking callbacks to static methods
- const assign = 'fActiveRecord::assign';
- const changed = 'fActiveRecord::changed';
- const checkConditions = 'fActiveRecord::checkConditions';
- const forceConfigure = 'fActiveRecord::forceConfigure';
- const hasOld = 'fActiveRecord::hasOld';
- const reset = 'fActiveRecord::reset';
- const retrieveOld = 'fActiveRecord::retrieveOld';
-
-
- /**
- * Caches callbacks for methods
- *
- * @var array
- */
- static protected $callback_cache = array();
-
- /**
- * An array of flags indicating a class has been configured
- *
- * @var array
- */
- static protected $configured = array();
-
-
- /**
- * Maps objects via their primary key
- *
- * @var array
- */
- static protected $identity_map = array();
-
-
- /**
- * Caches method name parsings
- *
- * @var array
- */
- static protected $method_name_cache = array();
-
-
- /**
- * Keeps track of the recursive call level of replication so we can clear the map
- *
- * @var integer
- */
- static protected $replicate_level = 0;
-
-
- /**
- * Keeps a list of records that have been replicated
- *
- * @var array
- */
- static protected $replicate_map = array();
-
- /**
- * Contains a list of what columns in each class need to be unescaped and what data type they are
- *
- * @var array
- */
- static protected $unescape_map = array();
-
-
- /**
- * Sets a value to the `$values` array, preserving the old value in `$old_values`
- *
- * @internal
- *
- * @param array &$values The current values
- * @param array &$old_values The old values
- * @param string $column The column to set
- * @param mixed $value The value to set
- * @return void
- */
- static public function assign(&$values, &$old_values, $column, $value)
- {
- if (!isset($old_values[$column])) {
- $old_values[$column] = array();
- }
-
- $old_values[$column][] = $values[$column];
- $values[$column] = $value;
- }
-
-
- /**
- * Checks to see if a value has changed
- *
- * @internal
- *
- * @param array &$values The current values
- * @param array &$old_values The old values
- * @param string $column The column to check
- * @return boolean If the value for the column specified has changed
- */
- static public function changed(&$values, &$old_values, $column)
- {
- if (!isset($old_values[$column])) {
- return FALSE;
- }
-
- // We do a strict comparison when one of the values is NULL since
- // NULL is almost always meant to be distinct from 0, FALSE, etc
- if ($old_values[$column][0] === NULL || $values[$column] === NULL) {
- return $old_values[$column][0] !== $values[$column];
- }
-
- return $old_values[$column][0] != $values[$column];
- }
-
-
- /**
- * Checks to see if a record matches a condition
- *
- * @internal
- *
- * @param string $operator The record to check
- * @param mixed $value The value to compare to
- * @param mixed $result The result of the method call(s)
- * @return boolean If the comparison was successful
- */
- static private function checkCondition($operator, $value, $result)
- {
- $was_array = is_array($value);
- if (!$was_array) { $value = array($value); }
- foreach ($value as $i => $_value) {
- if (is_object($_value)) {
- if ($_value instanceof fActiveRecord) {
- continue;
- }
- if (method_exists($_value, '__toString')) {
- $value[$i] = $_value->__toString();
- }
- }
- }
- if (!$was_array) { $value = $value[0]; }
-
- $was_array = is_array($result);
- if (!$was_array) { $result = array($result); }
- foreach ($result as $i => $_result) {
- if (is_object($_result)) {
- if ($_result instanceof fActiveRecord) {
- continue;
- }
- if (method_exists($_result, '__toString')) {
- $result[$i] = $_result->__toString();
- }
- }
- }
- if (!$was_array) { $result = $result[0]; }
-
- $match_all = $operator == '&~';
- $negate_like = $operator == '!~';
-
- switch ($operator) {
- case '&~':
- case '!~':
- case '~':
- if (!$match_all && !$negate_like && !is_array($value) && is_array($result)) {
- $value = fORMDatabase::parseSearchTerms($value, TRUE);
- }
-
- settype($value, 'array');
- settype($result, 'array');
-
- if (count($result) > 1) {
- foreach ($value as $_value) {
- $found = FALSE;
- foreach ($result as $_result) {
- if (fUTF8::ipos($_result, $_value) !== FALSE) {
- $found = TRUE;
- }
- }
- if (!$found) {
- return FALSE;
- }
- }
- } else {
- $found = FALSE;
- foreach ($value as $_value) {
- if (fUTF8::ipos($result[0], $_value) !== FALSE) {
- $found = TRUE;
- } elseif ($match_all) {
- return FALSE;
- }
- }
- if ((!$negate_like && !$found) || ($negate_like && $found)) {
- return FALSE;
- }
- }
- break;
-
- case '=':
- if ($value instanceof fActiveRecord && $result instanceof fActiveRecord) {
- if (get_class($value) != get_class($result) || !$value->exists() || !$result->exists() || self::hash($value) != self::hash($result)) {
- return FALSE;
- }
-
- } elseif (is_array($value) && !in_array($result, $value)) {
- return FALSE;
-
- } elseif (!is_array($value) && $result != $value) {
- return FALSE;
- }
- break;
-
- case '!':
- if ($value instanceof fActiveRecord && $result instanceof fActiveRecord) {
- if (get_class($value) == get_class($result) && $value->exists() && $result->exists() && self::hash($value) == self::hash($result)) {
- return FALSE;
- }
-
- } elseif (is_array($value) && in_array($result, $value)) {
- return FALSE;
-
- } elseif (!is_array($value) && $result == $value) {
- return FALSE;
- }
- break;
-
- case '<':
- if ($result >= $value) {
- return FALSE;
- }
- break;
-
- case '<=':
- if ($result > $value) {
- return FALSE;
- }
- break;
-
- case '>':
- if ($result <= $value) {
- return FALSE;
- }
- break;
-
- case '>=':
- if ($result < $value) {
- return FALSE;
- }
- break;
- }
-
- return TRUE;
- }
-
-
- /**
- * Checks to see if a record matches all of the conditions
- *
- * @internal
- *
- * @param fActiveRecord $record The record to check
- * @param array $conditions The conditions to check - see fRecordSet::filter() for format details
- * @return boolean If the record meets all conditions
- */
- static public function checkConditions($record, $conditions)
- {
- foreach ($conditions as $method => $value) {
-
- // Split the operator off of the end of the method name
- if (in_array(substr($method, -2), array('<=', '>=', '!=', '<>', '!~', '&~', '><'))) {
- $operator = strtr(
- substr($method, -2),
- array(
- '<>' => '!',
- '!=' => '!'
- )
- );
- $method = substr($method, 0, -2);
- } else {
- $operator = substr($method, -1);
- $method = substr($method, 0, -1);
- }
-
- if (preg_match('#(?<!\|)\|(?!\|)#', $method)) {
-
- $methods = explode('|', $method);
- $values = $value;
- $operators = array();
-
- foreach ($methods as &$_method) {
- if (in_array(substr($_method, -2), array('<=', '>=', '!=', '<>', '!~', '&~', '><'))) {
- $operators[] = strtr(
- substr($_method, -2),
- array(
- '<>' => '!',
- '!=' => '!'
- )
- );
- $_method = substr($_method, 0, -2);
- } elseif (!ctype_alnum(substr($_method, -1))) {
- $operators[] = substr($_method, -1);
- $_method = substr($_method, 0, -1);
- }
- }
- $operators[] = $operator;
-
-
- if (sizeof($operators) == 1) {
-
- // Handle fuzzy searches
- if ($operator == '~') {
-
- $results = array();
- foreach ($methods as $method) {
- $results[] = $record->$method();
- }
- if (!self::checkCondition($operator, $value, $results)) {
- return FALSE;
- }
-
- // Handle intersection
- } elseif ($operator == '><') {
-
- if (sizeof($methods) != 2 || sizeof($values) != 2) {
- throw new fProgrammerException(
- 'The intersection operator, %s, requires exactly two methods and two values',
- $operator
- );
- }
-
- $results = array();
- $results[0] = $record->{$methods[0]}();
- $results[1] = $record->{$methods[1]}();
-
- if ($results[1] === NULL && $values[1] === NULL) {
- if (!self::checkCondition('=', $values[0], $results[0])) {
- return FALSE;
- }
-
-
- } else {
-
- $starts_between_values = FALSE;
- $overlaps_value_1 = FALSE;
-
- if ($values[1] !== NULL) {
- $start_lt_value_1 = self::checkCondition('<', $values[0], $results[0]);
- $start_gt_value_2 = self::checkCondition('>', $values[1], $results[0]);
- $starts_between_values = !$start_lt_value_1 && !$start_gt_value_2;
- }
- if ($results[1] !== NULL) {
- $start_gt_value_1 = self::checkCondition('>', $values[0], $results[0]);
- $end_lt_value_1 = self::checkCondition('<', $values[0], $results[1]);
- $overlaps_value_1 = !$start_gt_value_1 && !$end_lt_value_1;
- }
-
- if (!$starts_between_values && !$overlaps_value_1) {
- return FALSE;
- }
- }
-
- } else {
- throw new fProgrammerException(
- 'An invalid comparison operator, %s, was specified for multiple columns',
- $operator
- );
- }
-
- // Handle OR conditions
- } else {
-
- if (sizeof($methods) != sizeof($values)) {
- throw new fProgrammerException(
- 'When performing an %1$s comparison there must be an equal number of methods and values, however there are not',
- 'OR',
- sizeof($methods),
- sizeof($values)
- );
- }
-
- if (sizeof($methods) != sizeof($operators)) {
- throw new fProgrammerException(
- 'When performing an %s comparison there must be a comparison operator for each column, however one or more is missing',
- 'OR'
- );
- }
-
- $results = array();
- $iterations = sizeof($methods);
- for ($i=0; $i<$iterations; $i++) {
- $results[] = self::checkCondition($operators[$i], $values[$i], $record->{$methods[$i]}());
- }
-
- if (!array_filter($results)) {
- return FALSE;
- }
-
- }
-
- // Single method comparisons
- } else {
- $result = $record->$method();
- if (!self::checkCondition($operator, $value, $result)) {
- return FALSE;
- }
- }
- }
-
- return TRUE;
- }
-
-
- /**
- * Composes text using fText if loaded
- *
- * @param string $message The message to compose
- * @param mixed $component A string or number to insert into the message
- * @param mixed ...
- * @return string The composed and possible translated message
- */
- static protected function compose($message)
- {
- $args = array_slice(func_get_args(), 1);
-
- if (class_exists('fText', FALSE)) {
- return call_user_func_array(
- array('fText', 'compose'),
- array($message, $args)
- );
- } else {
- return vsprintf($message, $args);
- }
- }
-
-
- /**
- * Ensures that ::configure() has been called for the class
- *
- * @internal
- *
- * @param string $class The class to configure
- * @return void
- */
- static public function forceConfigure($class)
- {
- if (isset(self::$configured[$class])) {
- return;
- }
- new $class();
- }
-
-
- /**
- * Takes a row of data or a primary key and makes a hash from the primary key
- *
- * @internal
- *
- * @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
- * @param string $class The class name, if $record isn't an fActiveRecord
- * @return string|NULL A hash of the record's primary key value or NULL if the record doesn't exist yet
- */
- static public function hash($record, $class=NULL)
- {
- if ($record instanceof fActiveRecord && !$record->exists()) {
- return NULL;
- }
-
- if ($class === NULL) {
- if (!$record instanceof fActiveRecord) {
- throw new fProgrammerException(
- 'The class of the record must be provided if the record specified is not an instance of fActiveRecord'
- );
- }
- $class = get_class($record);
- }
-
- $pk_columns = fORMSchema::retrieve()->getKeys(fORM::tablize($class), 'primary');
-
- // Build an array of just the primary key data
- $pk_data = array();
- foreach ($pk_columns as $pk_column) {
- if ($record instanceof fActiveRecord) {
- $value = (self::hasOld($record->old_values, $pk_column)) ? self::retrieveOld($record->old_values, $pk_column) : $record->values[$pk_column];
-
- } elseif (is_array($record)) {
- $value = $record[$pk_column];
-
- } else {
- $value = $record;
- }
-
- $pk_data[$pk_column] = fORM::scalarize(
- $class,
- $pk_column,
- $value
- );
-
- if (is_numeric($pk_data[$pk_column]) || is_object($pk_data[$pk_column])) {
- $pk_data[$pk_column] = (string) $pk_data[$pk_column];
- }
- }
-
- return md5(serialize($pk_data));
- }
-
-
- /**
- * Checks to see if an old value exists for a column
- *
- * @internal
- *
- * @param array &$old_values The old values
- * @param string $column The column to set
- * @return boolean If an old value for that column exists
- */
- static public function hasOld(&$old_values, $column)
- {
- return array_key_exists($column, $old_values);
- }
-
-
- /**
- * Resets the configuration of the class
- *
- * @internal
- *
- * @return void
- */
- static public function reset()
- {
- self::$callback_cache = array();
- self::$configured = array();
- self::$identity_map = array();
- self::$method_name_cache = array();
- self::$unescape_map = array();
- }
-
-
- /**
- * Retrieves the oldest value for a column or all old values
- *
- * @internal
- *
- * @param array &$old_values The old values
- * @param string $column The column to get
- * @param mixed $default The default value to return if no value exists
- * @param boolean $return_all Return the array of all old values for this column instead of just the oldest
- * @return mixed The old value for the column
- */
- static public function retrieveOld(&$old_values, $column, $default=NULL, $return_all=FALSE)
- {
- if (!isset($old_values[$column])) {
- return $default;
- }
-
- if ($return_all === TRUE) {
- return $old_values[$column];
- }
-
- return $old_values[$column][0];
- }
-
-
- /**
- * A data store for caching data related to a record, the structure of this is completely up to the developer using it
- *
- * @var array
- */
- protected $cache = array();
-
- /**
- * The old values for this record
- *
- * Column names are the keys, but a column key will only be present if a
- * value has changed. The value associated with each key is an array of
- * old values with the first entry being the oldest value. The static
- * methods ::assign(), ::changed(), ::hasOld() and ::retrieveOld() are the
- * best way to interact with this array.
- *
- * @var array
- */
- protected $old_values = array();
-
- /**
- * Records that are related to the current record via some relationship
- *
- * This array is used to cache related records so that a database query
- * is not required each time related records are accessed. The fORMRelated
- * class handles most of the interaction with this array.
- *
- * @var array
- */
- protected $related_records = array();
-
- /**
- * The values for this record
- *
- * This array always contains every column in the database table as a key
- * with the value being the current value.
- *
- * @var array
- */
- protected $values = array();
-
-
- /**
- * Handles all method calls for columns, related records and hook callbacks
- *
- * Dynamically handles `get`, `set`, `prepare`, `encode` and `inspect`
- * methods for each column in this record. Method names are in the form
- * `verbColumName()`.
- *
- * This method also handles `associate`, `build`, `count` and `link` verbs
- * for records in many-to-many relationships; `build`, `count` and
- * `populate` verbs for all related records in one-to-many relationships
- * and the `create` verb for all related records in *-to-one relationships.
- *
- * Method callbacks registered through fORM::registerActiveRecordMethod()
- * will be delegated via this method.
- *
- * @param string $method_name The name of the method called
- * @param array $parameters The parameters passed
- * @return mixed The value returned by the method called
- */
- public function __call($method_name, $parameters)
- {
- $class = get_class($this);
-
- if (!isset(self::$callback_cache[$class][$method_name])) {
- if (!isset(self::$callback_cache[$class])) {
- self::$callback_cache[$class] = array();
- }
- $callback = fORM::getActiveRecordMethod($class, $method_name);
- self::$callback_cache[$class][$method_name] = $callback ? $callback : FALSE;
- }
-
- if ($callback = self::$callback_cache[$class][$method_name]) {
- return call_user_func_array(
- $callback,
- array(
- $this,
- &$this->values,
- &$this->old_values,
- &$this->related_records,
- &$this->cache,
- $method_name,
- $parameters
- )
- );
- }
-
- if (!isset(self::$method_name_cache[$method_name])) {
- list ($action, $subject) = fORM::parseMethod($method_name);
- self::$method_name_cache[$method_name] = array(
- 'action' => $action,
- 'subject' => $subject
- );
- } else {
- $action = self::$method_name_cache[$method_name]['action'];
- $subject = self::$method_name_cache[$method_name]['subject'];
- }
-
- switch ($action) {
-
- // Value methods
- case 'get':
- return $this->get($subject);
-
- case 'encode':
- if (isset($parameters[0])) {
- return $this->encode($subject, $parameters[0]);
- }
- return $this->encode($subject);
-
- case 'prepare':
- if (isset($parameters[0])) {
- return $this->prepare($subject, $parameters[0]);
- }
- return $this->prepare($subject);
-
- case 'inspect':
- if (isset($parameters[0])) {
- return $this->inspect($subject, $parameters[0]);
- }
- return $this->inspect($subject);
-
- case 'set':
- if (sizeof($parameters) < 1) {
- throw new fProgrammerException(
- 'The method, %s(), requires at least one parameter',
- $method_name
- );
- }
- return $this->set($subject, $parameters[0]);
-
- // Related data methods
- case 'associate':
- if (sizeof($parameters) < 1) {
- throw new fProgrammerException(
- 'The method, %s(), requires at least one parameter',
- $method_name
- );
- }
-
- $table = fORM::tablize($class);
- $records = $parameters[0];
- $route = isset($parameters[1]) ? $parameters[1] : NULL;
- $plural = FALSE;
-
- // one-to-many relationships need to use plural forms
- if (in_array($subject, fORMSchema::retrieve()->getTables())) {
- if (fORMSchema::isOneToOne($table, $subject, $route)) {
- throw new fProgrammerException(
- 'The table %1$s is not in a %2$srelationship with the table %3$s',
- $table,
- '*-to-many ',
- $subject
- );
- }
- $subject = fGrammar::singularize($subject);
- $plural = TRUE;
- }
- $subject = fGrammar::camelize($subject, TRUE);
-
- // This handles one-to-many and many-to-many relationships
- if ($plural) {
- return fORMRelated::associateRecords($class, $this->related_records, $subject, $records, $route);
- }
-
- // This handles one-to-one relationships
- return fORMRelated::associateRecord($class, $this->related_records, $subject, $records, $route);
-
- case 'build':
- $subject = fGrammar::singularize($subject);
- $subject = fGrammar::camelize($subject, TRUE);
-
- if (isset($parameters[0])) {
- return fORMRelated::buildRecords($class, $this->values, $this->related_records, $subject, $parameters[0]);
- }
- return fORMRelated::buildRecords($class, $this->values, $this->related_records, $subject);
-
- case 'count':
- $subject = fGrammar::singularize($subject);
- $subject = fGrammar::camelize($subject, TRUE);
-
- if (isset($parameters[0])) {
- return fORMRelated::countRecords($class, $this->values, $this->related_records, $subject, $parameters[0]);
- }
- return fORMRelated::countRecords($class, $this->values, $this->related_records, $subject);
-
- case 'create':
- $subject = fGrammar::camelize($subject, TRUE);
-
- if (isset($parameters[0])) {
- return fORMRelated::createRecord($class, $this->values, $this->related_records, $subject, $parameters[0]);
- }
- return fORMRelated::createRecord($class, $this->values, $this->related_records, $subject);
-
- case 'inject':
- if (sizeof($parameters) < 1) {
- throw new fProgrammerException(
- 'The method, %s(), requires at least one parameter',
- $method_name
- );
- }
-
- $subject = fGrammar::singularize($subject);
- $subject = fGrammar::camelize($subject, TRUE);
-
- if (isset($parameters[1])) {
- return fORMRelated::setRecordSet($class, $this->related_records, $subject, $parameters[0], $parameters[1]);
- }
- return fORMRelated::setRecordSet($class, $this->related_records, $subject, $parameters[0]);
-
- case 'link':
- $subject = fGrammar::singularize($subject);
- $subject = fGrammar::camelize($subject, TRUE);
-
- if (isset($parameters[0])) {
- return fORMRelated::linkRecords($class, $this->related_records, $subject, $parameters[0]);
- }
- return fORMRelated::linkRecords($class, $this->related_records, $subject);
-
- case 'list':
- $subject = fGrammar::singularize($subject);
- $subject = fGrammar::camelize($subject, TRUE);
-
- if (isset($parameters[0])) {
- return fORMRelated::getPrimaryKeys($class, $this->values, $this->related_records, $subject, $parameters[0]);
- }
- return fORMRelated::getPrimaryKeys($class, $this->values, $this->related_records, $subject);
-
- case 'populate':
- $table = fORM::tablize($class);
- $route = isset($parameters[0]) ? $parameters[0] : NULL;
-
- // one-to-many relationships need to use plural forms
- if (in_array($subject, fORMSchema::retrieve()->getTables())) {
- if (fORMSchema::isOneToOne($table, $subject, $route)) {
- throw new fProgrammerException(
- 'The table %1$s is not in a%2$srelationship with the table %3$s',
- $table,
- ' one-to-many ',
- $subject
- );
- }
- $subject = fGrammar::singularize($subject);
- }
-
- $subject = fGrammar::camelize($subject, TRUE);
-
- return fORMRelated::populateRecords($class, $this->related_records, $subject, $route);
-
- case 'tally':
- if (sizeof($parameters) < 1) {
- throw new fProgrammerException(
- 'The method, %s(), requires at least one parameter',
- $method_name
- );
- }
-
- $subject = fGrammar::singularize($subject);
- $subject = fGrammar::camelize($subject, TRUE);
-
- if (isset($parameters[1])) {
- return fORMRelated::setCount($class, $this->related_records, $subject, $parameters[0], $parameters[1]);
- }
- return fORMRelated::setCount($class, $this->related_records, $subject, $parameters[0]);
-
- // Error handler
- default:
- throw new fProgrammerException(
- 'Unknown method, %s(), called',
- $method_name
- );
- }
- }
-
-
- /**
- * Creates a clone of a record
- *
- * If the record has an auto incrementing primary key, the primary key will
- * be erased in the clone. If the primary key is not auto incrementing,
- * the primary key will be left as-is in the clone. In either situation the
- * clone will return `FALSE` from the ::exists() method until ::store() is
- * called.
- *
- * @internal
- *
- * @return fActiveRecord
- */
- public function __clone()
- {
- $class = get_class($this);
-
- // Copy values and cache, making sure objects are cloned to prevent reference issues
- $temp_values = $this->values;
- $new_values = array();
- $this->values =& $new_values;
- foreach ($temp_values as $column => $value) {
- $this->values[$column] = fORM::replicate($class, $column, $value);
- }
-
- $temp_cache = $this->cache;
- $new_cache = array();
- $this->cache =& $new_cache;
- foreach ($temp_cache as $key => $value) {
- if (is_object($value)) {
- $this->cache[$key] = clone $value;
- } else {
- $this->cache[$key] = $value;
- }
- }
-
- // Related records are purged
- $new_related_records = array();
- $this->related_records =& $new_related_records;
-
- // Old values are changed to look like the record is non-existant
- $new_old_values = array();
- $this->old_values =& $new_old_values;
-
- foreach (array_keys($this->values) as $key) {
- $this->old_values[$key] = array(NULL);
- }
-
- // If we have a single auto incrementing primary key, remove the value
- $table = fORM::tablize($class);
- $pk_columns = fORMSchema::retrieve()->getKeys($table, 'primary');
-
- if (sizeof($pk_columns) == 1 && fORMSchema::retrieve()->getColumnInfo($table, $pk_columns[0], 'auto_increment')) {
- $this->values[$pk_columns[0]] = NULL;
- unset($this->old_values[$pk_columns[0]]);
- }
- }
-
-
- /**
- * Creates a new record or loads one from the database - if a primary key or unique key is provided the record will be loaded
- *
- * @throws fNotFoundException When the record specified by `$key` can not be found in the database
- *
- * @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}`
- * @return fActiveRecord
- */
- public function __construct($key=NULL)
- {
- $class = get_class($this);
-
- // If the features of this class haven't been set yet, do it
- if (!isset(self::$configured[$class])) {
- $this->configure();
- self::$configured[$class] = TRUE;
-
- $table = fORM::tablize($class);
- if (!fORMSchema::retrieve()->getKeys($table, 'primary')) {
- throw new fProgrammerException(
- '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.',
- $table,
- $class,
- 'fActiveRecord',
- 'fRecordSet'
- );
- }
-
- // If the configuration was forced, prevent the post::__construct() hook from
- // being triggered since it is not really a real record instantiation
- $trace = array_slice(debug_backtrace(), 0, 2);
-
- $is_forced = sizeof($trace) == 2;
- $is_forced = $is_forced && $trace[1]['function'] == 'forceConfigure';
- $is_forced = $is_forced && isset($trace[1]['class']);
- $is_forced = $is_forced && $trace[1]['type'] == '::';
- $is_forced = $is_forced && in_array($trace[1]['class'], array('fActiveRecord', $class));
-
- if ($is_forced) {
- return;
- }
- }
-
- if (!isset(self::$callback_cache[$class]['__construct'])) {
- if (!isset(self::$callback_cache[$class])) {
- self::$callback_cache[$class] = array();
- }
- $callback = fORM::getActiveRecordMethod($class, '__construct');
- self::$callback_cache[$class]['__construct'] = $callback ? $callback : FALSE;
- }
- if ($callback = self::$callback_cache[$class]['__construct']) {
- return $this->__call($callback);
- }
-
- // Handle loading by a result object passed via the fRecordSet class
- if ($key instanceof Iterator) {
-
- if ($this->loadFromResult($key)) {
- return;
- }
-
- // Handle loading an object from the database
- } elseif ($key !== NULL) {
-
- $table = fORM::tablize($class);
- $pk_columns = fORMSchema::retrieve()->getKeys($table, 'primary');
-
- // If the primary key does not look properly formatted, check to see if it is a UNIQUE key
- $is_unique_key = FALSE;
- if (is_array($key) && (sizeof($pk_columns) == 1 || array_diff(array_keys($key), $pk_columns))) {
- $unique_keys = fORMSchema::retrieve()->getKeys($table, 'unique');
- $key_keys = array_keys($key);
- foreach ($unique_keys as $unique_key) {
- if (!array_diff($key_keys, $unique_key)) {
- $is_unique_key = TRUE;
- }
- }
- }
-
- $wrong_keys = is_array($key) && array_diff(array_keys($key), $pk_columns);
- $wrong_type = !is_array($key) && (sizeof($pk_columns) != 1 || !is_scalar($key));
-
- // If we didn't find a UNIQUE key and primary key doesn't look right we fail
- if (!$is_unique_key && ($wrong_keys || $wrong_type)) {
- throw new fProgrammerException(
- 'An invalidly formatted primary or unique key was passed to this %s object',
- fORM::getRecordName($class)
- );
- }
-
- if ($is_unique_key) {
-
- $result = $this->fetchResultFromUniqueKey($key);
- if ($this->loadFromResult($result)) {
- return;
- }
-
- } else {
-
- $hash = self::hash($key, $class);
- if ($this->loadFromIdentityMap($key, $hash)) {
- return;
- }
-
- // Assign the primary key values for loading
- if (is_array($key)) {
- foreach ($pk_columns as $pk_column) {
- $this->values[$pk_column] = $key[$pk_column];
- }
- } else {
- $this->values[$pk_columns[0]] = $key;
- }
-
- $this->load();
- }
-
- // Create an empty array for new objects
- } else {
- $column_info = fORMSchema::retrieve()->getColumnInfo(fORM::tablize($class));
- foreach ($column_info as $column => $info) {
- $this->values[$column] = NULL;
- if ($info['default'] !== NULL) {
- self::assign(
- $this->values,
- $this->old_values,
- $column,
- fORM::objectify($class, $column, $info['default'])
- );
- }
- }
- }
-
- fORM::callHookCallbacks(
- $this,
- 'post::__construct()',
- $this->values,
- $this->old_values,
- $this->related_records,
- $this->cache
- );
- }
-
-
- /**
- * All requests that hit this method should be requests for callbacks
- *
- * @internal
- *
- * @param string $method The method to create a callback for
- * @return callback The callback for the method requested
- */
- public function __get($method)
- {
- return array($this, $method);
- }
-
-
- /**
- * Configure itself when coming out of the session. Records from the session are NOT hooked into the identity map.
- *
- * @internal
- *
- * @return void
- */
- public function __wakeup()
- {
- $class = get_class($this);
-
- if (!isset(self::$configured[$class])) {
- $this->configure();
- self::$configured[$class] = TRUE;
- }
- }
-
-
- /**
- * Allows the programmer to set features for the class
- *
- * This method is only called once per page load for each class.
- *
- * @return void
- */
- protected function configure()
- {
- }
-
-
- /**
- * Creates the SQL to insert this record
- *
- * @param array $sql_values The SQL-formatted values for this record
- * @return string The SQL insert statement
- */
- protected function constructInsertSQL($sql_values)
- {
- $sql = 'INSERT INTO ' . fORM::tablize(get_class($this)) . ' (';
-
- $columns = '';
- $values = '';
-
- $column_num = 0;
- foreach ($sql_values as $column => $sql_value) {
- if ($column_num) { $columns .= ', '; $values .= ', '; }
- $columns .= $column;
- $values .= $sql_value;
- $column_num++;
- }
- $sql .= $columns . ') VALUES (' . $values . ')';
- return $sql;
- }
-
-
- /**
- * Creates the SQL to update this record
- *
- * @param array $sql_values The SQL-formatted values for this record
- * @return string The SQL update statement
- */
- protected function constructUpdateSQL($sql_values)
- {
- $table = fORM::tablize(get_class($this));
-
- $sql = 'UPDATE ' . $table . ' SET ';
- $column_num = 0;
- foreach ($sql_values as $column => $sql_value) {
- if ($column_num) { $sql .= ', '; }
- $sql .= $column . ' = ' . $sql_value;
- $column_num++;
- }
-
- $sql .= ' WHERE ' . fORMDatabase::createPrimaryKeyWhereClause($table, $table, $this->values, $this->old_values);
-
- return $sql;
- }
-
-
- /**
- * Deletes a record from the database, but does not destroy the object
- *
- * This method will start a database transaction if one is not already active.
- *
- * @return fActiveRecord The record object, to allow for method chaining
- */
- public function delete()
- {
- $class = get_class($this);
-
- if (fORM::getActiveRecordMethod($class, 'delete')) {
- return $this->__call('delete', array());
- }
-
- if (!$this->exists()) {
- throw new fProgrammerException(
- 'This %s object does not yet exist in the database, and thus can not be deleted',
- fORM::getRecordName($class)
- );
- }
-
- fORM::callHookCallbacks(
- $this,
- 'pre::delete()',
- $this->values,
- $this->old_values,
- $this->related_records,
- $this->cache
- );
-
- $table = fORM::tablize($class);
-
- $inside_db_transaction = fORMDatabase::retrieve()->isInsideTransaction();
-
- try {
-
- if (!$inside_db_transaction) {
- fORMDatabase::retrieve()->translatedQuery('BEGIN');
- }
-
- fORM::callHookCallbacks(
- $this,
- 'post-begin::delete()',
- $this->values,
- $this->old_values,
- $this->related_records,
- $this->cache
- );
-
- // Check to ensure no foreign dependencies prevent deletion
- $one_to_many_relationships = fORMSchema::retrieve()->getRelationships($table, 'one-to-many');
- $many_to_many_relationships = fORMSchema::retrieve()->getRelationships($table, 'many-to-many');
-
- $relationships = array_merge($one_to_many_relationships, $many_to_many_relationships);
- $records_sets_to_delete = array();
-
- $restriction_messages = array();
-
- foreach ($relationships as $relationship) {
-
- // Figure out how to check for related records
- $type = (isset($relationship['join_table'])) ? 'many-to-many' : 'one-to-many';
- $route = fORMSchema::getRouteNameFromRelationship($type, $relationship);
-
- $related_class = fORM::classize($relationship['related_table']);
- $related_objects = fGrammar::pluralize($related_class);
- $method = 'build' . $related_objects;
-
- // Grab the related records
- $record_set = $this->$method($route);
-
- // If there are none, we can just move on
- if (!$record_set->count()) {
- continue;
- }
-
- if ($type == 'one-to-many' && $relationship['on_delete'] == 'cascade') {
- $records_sets_to_delete[] = $record_set;
- }
-
- if ($relationship['on_delete'] == 'restrict' || $relationship['on_delete'] == 'no_action') {
-
- // Otherwise we have a restriction
- $related_class_name = fORM::classize($relationship['related_table']);
- $related_record_name = fORM::getRecordName($related_class_name);
- $related_record_name = fGrammar::pluralize($related_record_name);
-
- $restriction_messages[] = self::compose("One or more %s references it", $related_record_name);
- }
- }
-
- if ($restriction_messages) {
- throw new fValidationException(
- self::compose('This %s can not be deleted because:', fORM::getRecordName($class)),
- $restriction_messages
- );
- }
-
-
- // Delete this record
- $sql = 'DELETE FROM ' . $table . ' WHERE ' . fORMDatabase::createPrimaryKeyWhereClause($table, $table, $this->values, $this->old_values);
- $result = fORMDatabase::retrieve()->translatedQuery($sql);
-
-
- // Delete related records
- foreach ($records_sets_to_delete as $record_set) {
- foreach ($record_set as $record) {
- if ($record->exists()) {
- $record->delete();
- }
- }
- }
-
- fORM::callHookCallbacks(
- $this,
- 'pre-commit::delete()',
- $this->values,
- $this->old_values,
- $this->related_records,
- $this->cache
- );
-
- if (!$inside_db_transaction) {
- fORMDatabase::retrieve()->translatedQuery('COMMIT');
- }
-
- fORM::callHookCallbacks(
- $this,
- 'post-commit::delete()',
- $this->values,
- $this->old_values,
- $this->related_records,
- $this->cache
- );
-
- } catch (fException $e) {
-
- if (!$inside_db_transaction) {
- fORMDatabase::retrieve()->translatedQuery('ROLLBACK');
- }
-
- fORM::callHookCallbacks(
- $this,
- 'post-rollback::delete()',
- $this->values,
- $this->old_values,
- $this->related_records,
- $this->cache
- );
-
- // Check to see if the validation exception came from a related record, and fix the message
- if ($e instanceof fValidationException) {
- $message = $e->getMessage();
- $search = self::compose('This %s can not be deleted because:', fORM::getRecordName($class));
- if (stripos($message, $search) === FALSE) {
- $regex = self::compose('This %s can not be deleted because:', '__');
- $regex_parts = explode('__', $regex);
- $regex = '#(' . preg_quote($regex_parts[0], '#') . ').*?(' . preg_quote($regex_parts[0], '#') . ')#';
-
- $message = preg_replace($regex, '\1' . strtr(fORM::getRecordName($class), array('\\' => '\\\\', '$' => '\\$')) . '\2', $message);
-
- $find = self::compose("One or more %s references it", '__');
- $find_parts = explode('__', $find);
- $find_regex = '#' . preg_quote($find_parts[0], '#') . '(.*?)' . preg_quote($find_parts[1], '#') . '#';
-
- $replace = self::compose("One or more %s indirectly references it", '__');
- $replace_parts = explode('__', $replace);
- $replace_regex = strtr($replace_parts[0], array('\\' => '\\\\', '$' => '\\$')) . '\1' . strtr($replace_parts[1], array('\\' => '\\\\', '$' => '\\$'));
-
- $message = preg_replace($find_regex, $replace_regex, $regex);
- throw new fValidationException($message);
- }
- }
-
- throw $e;
- }
-
- fORM::callHookCallbacks(
- $this,
- 'post::delete()',
- $this->values,
- $this->old_values,
- $this->related_records,
- $this->cache
- );
-
- // If we just deleted an object that has an auto-incrementing primary key,
- // lets delete that value from the object since it is no longer valid
- $pk_columns = fORMSchema::retrieve()->getKeys($table, 'primary');
- if (sizeof($pk_columns) == 1 && fORMSchema::retrieve()->getColumnInfo($table, $pk_columns[0], 'auto_increment')) {
- $this->values[$pk_columns[0]] = NULL;
- unset($this->old_values[$pk_columns[0]]);
- }
-
- return $this;
- }
-
-
- /**
- * Retrieves a value from the record and prepares it for output into an HTML form element.
- *
- * Below are the transformations performed:
- *
- * - **varchar, char, text**: will run through fHTML::encode(), if `TRUE` is passed the text will be run through fHTML::convertNewLinks() and fHTML::makeLinks()
- * - **float**: takes 1 parameter to specify the number of decimal places
- * - **date, time, timestamp**: `format()` will be called on the fDate/fTime/fTimestamp object with the 1 parameter specified
- * - **objects**: the object will be converted to a string by `__toString()` or a `(string)` cast and then will be run through fHTML::encode()
- * - **all other data types**: the value will be run through fHTML::encode()
- *
- * @param string $column The name of the column to retrieve
- * @param string $formatting The formatting string
- * @return string The encoded value for the column specified
- */
- protected function encode($column, $formatting=NULL)
- {
- if (!array_key_exists($column, $this->values)) {
- throw new fProgrammerException(
- 'The column specified, %s, does not exist',
- $column
- );
- }
-
- $table = fORM::tablize(get_class($this));
- $column_type = fORMSchema::retrieve()->getColumnInfo($table, $column, 'type');
-
- // Ensure the programmer is calling the function properly
- if ($column_type == 'blob') {
- throw new fProgrammerException(
- 'The column specified, %s, does not support forming because it is a blob column',
- $column
- );
- }
-
- if ($formatting !== NULL && in_array($column_type, array('boolean', 'integer'))) {
- throw new fProgrammerException(
- 'The column specified, %s, does not support any formatting options',
- $column
- );
- }
-
- // Grab the value for empty value checking
- $method_name = 'get' . fGrammar::camelize($column, TRUE);
- $value = $this->$method_name();
-
- // Date/time objects
- if (is_object($value) && in_array($column_type, array('date', 'time', 'timestamp'))) {
- if ($formatting === NULL) {
- throw new fProgrammerException(
- 'The column specified, %s, requires one formatting parameter, a valid date() formatting string',
- $column
- );
- }
- $value = $value->format($formatting);
- }
-
- // Other objects
- if (is_object($value) && is_callable(array($value, '__toString'))) {
- $value = $value->__toString();
- } elseif (is_object($value)) {
- $value = (string) $value;
- }
-
- // Make sure we don't mangle a non-float value
- if ($column_type == 'float' && is_numeric($value)) {
- $column_decimal_places = fORMSchema::retrieve()->getColumnInfo($table, $column, 'decimal_places');
-
- // If the user passed in a formatting value, use it
- if ($formatting !== NULL && is_numeric($formatting)) {
- $decimal_places = (int) $formatting;
-
- // If the column has a pre-defined number of decimal places, use that
- } elseif ($column_decimal_places !== NULL) {
- $decimal_places = $column_decimal_places;
-
- // This figures out how many decimal places are part of the current value
- } else {
- $value_parts = explode('.', $value);
- $decimal_places = (!isset($value_parts[1])) ? 0 : strlen($value_parts[1]);
- }
-
- return number_format($value, $decimal_places, '.', '');
- }
-
- // Turn line-breaks into breaks for text fields and add links
- if ($formatting === TRUE && in_array($column_type, array('varchar', 'char', 'text'))) {
- return fHTML::makeLinks(fHTML::convertNewlines(fHTML::encode($value)));
- }
-
- // Anything that has gotten to here is a string value or is not the proper data type for the column that contains it
- return fHTML::encode($value);
- }
-
-
- /**
- * Checks to see if the record exists in the database
- *
- * @return boolean If the record exists in the database
- */
- public function exists()
- {
- $class = get_class($this);
-
- if (fORM::getActiveRecordMethod($class, 'exists')) {
- return $this->__call('exists', array());
- }
-
- $pk_columns = fORMSchema::retrieve()->getKeys(fORM::tablize($class), 'primary');
- $exists = FALSE;
-
- foreach ($pk_columns as $pk_column) {
- $has_old = self::hasOld($this->old_values, $pk_column);
- if (($has_old && self::retrieveOld($this->old_values, $pk_column) !== NULL) || (!$has_old && $this->values[$pk_column] !== NULL)) {
- $exists = TRUE;
- }
- }
-
- return $exists;
- }
-
-
- /**
- * Loads a record from t…
Large files files are truncated, but you can click here to view the full file