/lib/Cake/Model/Model.php
PHP | 3640 lines | 2049 code | 291 blank | 1300 comment | 606 complexity | 4e72c2161c76a8ea0818b27175dbfb88 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- * Object-relational mapper.
- *
- * DBO-backed object data model, for mapping database tables to Cake objects.
- *
- * PHP versions 5
- *
- * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
- * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
- *
- * Licensed under The MIT License
- * Redistributions of files must retain the above copyright notice.
- *
- * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
- * @link http://cakephp.org CakePHP(tm) Project
- * @package Cake.Model
- * @since CakePHP(tm) v 0.10.0.0
- * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
- */
- App::uses('ClassRegistry', 'Utility');
- App::uses('Validation', 'Utility');
- App::uses('String', 'Utility');
- App::uses('Set', 'Utility');
- App::uses('BehaviorCollection', 'Model');
- App::uses('ModelBehavior', 'Model');
- App::uses('ConnectionManager', 'Model');
- App::uses('Xml', 'Utility');
- App::uses('CakeEvent', 'Event');
- App::uses('CakeEventListener', 'Event');
- App::uses('CakeEventManager', 'Event');
- /**
- * Object-relational mapper.
- *
- * DBO-backed object data model.
- * Automatically selects a database table name based on a pluralized lowercase object class name
- * (i.e. class 'User' => table 'users'; class 'Man' => table 'men')
- * The table is required to have at least 'id auto_increment' primary key.
- *
- * @package Cake.Model
- * @link http://book.cakephp.org/2.0/en/models.html
- */
- class Model extends Object implements CakeEventListener {
- /**
- * The name of the DataSource connection that this Model uses
- *
- * The value must be an attribute name that you defined in `app/Config/database.php`
- * or created using `ConnectionManager::create()`.
- *
- * @var string
- * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#usedbconfig
- */
- public $useDbConfig = 'default';
- /**
- * Custom database table name, or null/false if no table association is desired.
- *
- * @var string
- * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#useTable
- */
- public $useTable = null;
- /**
- * Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements.
- *
- * This field is also used in `find('list')` when called with no extra parameters in the fields list
- *
- * @var string
- * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#displayField
- */
- public $displayField = null;
- /**
- * Value of the primary key ID of the record that this model is currently pointing to.
- * Automatically set after database insertions.
- *
- * @var mixed
- */
- public $id = false;
- /**
- * Container for the data that this model gets from persistent storage (usually, a database).
- *
- * @var array
- * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#data
- */
- public $data = array();
- /**
- * Holds physical schema/database name for this model. Automatically set during Model creation.
- *
- * @var string
- * @access public
- */
- public $schemaName = null;
- /**
- * Table name for this Model.
- *
- * @var string
- */
- public $table = false;
- /**
- * The name of the primary key field for this model.
- *
- * @var string
- * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#primaryKey
- */
- public $primaryKey = null;
- /**
- * Field-by-field table metadata.
- *
- * @var array
- */
- protected $_schema = null;
- /**
- * List of validation rules. It must be an array with the field name as key and using
- * as value one of the following possibilities
- *
- * ### Validating using regular expressions
- *
- * {{{
- * public $validate = array(
- * 'name' => '/^[a-z].+$/i'
- * );
- * }}}
- *
- * ### Validating using methods (no parameters)
- *
- * {{{
- * public $validate = array(
- * 'name' => 'notEmpty'
- * );
- * }}}
- *
- * ### Validating using methods (with parameters)
- *
- * {{{
- * public $validate = array(
- * 'age' => array(
- * 'rule' => array('between', 5, 25)
- * )
- * );
- * }}}
- *
- * ### Validating using custom method
- *
- * {{{
- * public $validate = array(
- * 'password' => array(
- * 'rule' => array('customValidation')
- * )
- * );
- * public function customValidation($data) {
- * // $data will contain array('password' => 'value')
- * if (isset($this->data[$this->alias]['password2'])) {
- * return $this->data[$this->alias]['password2'] === current($data);
- * }
- * return true;
- * }
- * }}}
- *
- * ### Validations with messages
- *
- * The messages will be used in Model::$validationErrors and can be used in the FormHelper
- *
- * {{{
- * public $validate = array(
- * 'age' => array(
- * 'rule' => array('between', 5, 25),
- * 'message' => array('The age must be between %d and %d.')
- * )
- * );
- * }}}
- *
- * ### Multiple validations to the same field
- *
- * {{{
- * public $validate = array(
- * 'login' => array(
- * array(
- * 'rule' => 'alphaNumeric',
- * 'message' => 'Only alphabets and numbers allowed',
- * 'last' => true
- * ),
- * array(
- * 'rule' => array('minLength', 8),
- * 'message' => array('Minimum length of %d characters')
- * )
- * )
- * );
- * }}}
- *
- * ### Valid keys in validations
- *
- * - `rule`: String with method name, regular expression (started by slash) or array with method and parameters
- * - `message`: String with the message or array if have multiple parameters. See http://php.net/sprintf
- * - `last`: Boolean value to indicate if continue validating the others rules if the current fail [Default: true]
- * - `required`: Boolean value to indicate if the field must be present on save
- * - `allowEmpty`: Boolean value to indicate if the field can be empty
- * - `on`: Possible values: `update`, `create`. Indicate to apply this rule only on update or create
- *
- * @var array
- * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#validate
- * @link http://book.cakephp.org/2.0/en/models/data-validation.html
- */
- public $validate = array();
- /**
- * List of validation errors.
- *
- * @var array
- */
- public $validationErrors = array();
- /**
- * Name of the validation string domain to use when translating validation errors.
- *
- * @var string
- */
- public $validationDomain = null;
- /**
- * Database table prefix for tables in model.
- *
- * @var string
- * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#tableprefix
- */
- public $tablePrefix = null;
- /**
- * Name of the model.
- *
- * @var string
- * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#name
- */
- public $name = null;
- /**
- * Alias name for model.
- *
- * @var string
- */
- public $alias = null;
- /**
- * List of table names included in the model description. Used for associations.
- *
- * @var array
- */
- public $tableToModel = array();
- /**
- * Whether or not to cache queries for this model. This enables in-memory
- * caching only, the results are not stored beyond the current request.
- *
- * @var boolean
- * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#cacheQueries
- */
- public $cacheQueries = false;
- /**
- * Detailed list of belongsTo associations.
- *
- * ### Basic usage
- *
- * `public $belongsTo = array('Group', 'Department');`
- *
- * ### Detailed configuration
- *
- * {{{
- * public $belongsTo = array(
- * 'Group',
- * 'Department' => array(
- * 'className' => 'Department',
- * 'foreignKey' => 'department_id'
- * )
- * );
- * }}}
- *
- * ### Possible keys in association
- *
- * - `className`: the classname of the model being associated to the current model.
- * If you're defining a 'Profile belongsTo User' relationship, the className key should equal 'User.'
- * - `foreignKey`: the name of the foreign key found in the current model. This is
- * especially handy if you need to define multiple belongsTo relationships. The default
- * value for this key is the underscored, singular name of the other model, suffixed with '_id'.
- * - `conditions`: An SQL fragment used to filter related model records. It's good
- * practice to use model names in SQL fragments: 'User.active = 1' is always
- * better than just 'active = 1.'
- * - `type`: the type of the join to use in the SQL query, default is LEFT which
- * may not fit your needs in all situations, INNER may be helpful when you want
- * everything from your main and associated models or nothing at all!(effective
- * when used with some conditions of course). (NB: type value is in lower case - i.e. left, inner)
- * - `fields`: A list of fields to be retrieved when the associated model data is
- * fetched. Returns all fields by default.
- * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
- * - `counterCache`: If set to true the associated Model will automatically increase or
- * decrease the "[singular_model_name]_count" field in the foreign table whenever you do
- * a save() or delete(). If its a string then its the field name to use. The value in the
- * counter field represents the number of related rows.
- * - `counterScope`: Optional conditions array to use for updating counter cache field.
- *
- * @var array
- * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#belongsto
- */
- public $belongsTo = array();
- /**
- * Detailed list of hasOne associations.
- *
- * ### Basic usage
- *
- * `public $hasOne = array('Profile', 'Address');`
- *
- * ### Detailed configuration
- *
- * {{{
- * public $hasOne = array(
- * 'Profile',
- * 'Address' => array(
- * 'className' => 'Address',
- * 'foreignKey' => 'user_id'
- * )
- * );
- * }}}
- *
- * ### Possible keys in association
- *
- * - `className`: the classname of the model being associated to the current model.
- * If you're defining a 'User hasOne Profile' relationship, the className key should equal 'Profile.'
- * - `foreignKey`: the name of the foreign key found in the other model. This is
- * especially handy if you need to define multiple hasOne relationships.
- * The default value for this key is the underscored, singular name of the
- * current model, suffixed with '_id'. In the example above it would default to 'user_id'.
- * - `conditions`: An SQL fragment used to filter related model records. It's good
- * practice to use model names in SQL fragments: "Profile.approved = 1" is
- * always better than just "approved = 1."
- * - `fields`: A list of fields to be retrieved when the associated model data is
- * fetched. Returns all fields by default.
- * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
- * - `dependent`: When the dependent key is set to true, and the model's delete()
- * method is called with the cascade parameter set to true, associated model
- * records are also deleted. In this case we set it true so that deleting a
- * User will also delete her associated Profile.
- *
- * @var array
- * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasone
- */
- public $hasOne = array();
- /**
- * Detailed list of hasMany associations.
- *
- * ### Basic usage
- *
- * `public $hasMany = array('Comment', 'Task');`
- *
- * ### Detailed configuration
- *
- * {{{
- * public $hasMany = array(
- * 'Comment',
- * 'Task' => array(
- * 'className' => 'Task',
- * 'foreignKey' => 'user_id'
- * )
- * );
- * }}}
- *
- * ### Possible keys in association
- *
- * - `className`: the classname of the model being associated to the current model.
- * If you're defining a 'User hasMany Comment' relationship, the className key should equal 'Comment.'
- * - `foreignKey`: the name of the foreign key found in the other model. This is
- * especially handy if you need to define multiple hasMany relationships. The default
- * value for this key is the underscored, singular name of the actual model, suffixed with '_id'.
- * - `conditions`: An SQL fragment used to filter related model records. It's good
- * practice to use model names in SQL fragments: "Comment.status = 1" is always
- * better than just "status = 1."
- * - `fields`: A list of fields to be retrieved when the associated model data is
- * fetched. Returns all fields by default.
- * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
- * - `limit`: The maximum number of associated rows you want returned.
- * - `offset`: The number of associated rows to skip over (given the current
- * conditions and order) before fetching and associating.
- * - `dependent`: When dependent is set to true, recursive model deletion is
- * possible. In this example, Comment records will be deleted when their
- * associated User record has been deleted.
- * - `exclusive`: When exclusive is set to true, recursive model deletion does
- * the delete with a deleteAll() call, instead of deleting each entity separately.
- * This greatly improves performance, but may not be ideal for all circumstances.
- * - `finderQuery`: A complete SQL query CakePHP can use to fetch associated model
- * records. This should be used in situations that require very custom results.
- *
- * @var array
- * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany
- */
- public $hasMany = array();
- /**
- * Detailed list of hasAndBelongsToMany associations.
- *
- * ### Basic usage
- *
- * `public $hasAndBelongsToMany = array('Role', 'Address');`
- *
- * ### Detailed configuration
- *
- * {{{
- * public $hasAndBelongsToMany = array(
- * 'Role',
- * 'Address' => array(
- * 'className' => 'Address',
- * 'foreignKey' => 'user_id',
- * 'associationForeignKey' => 'address_id',
- * 'joinTable' => 'addresses_users'
- * )
- * );
- * }}}
- *
- * ### Possible keys in association
- *
- * - `className`: the classname of the model being associated to the current model.
- * If you're defining a 'Recipe HABTM Tag' relationship, the className key should equal 'Tag.'
- * - `joinTable`: The name of the join table used in this association (if the
- * current table doesn't adhere to the naming convention for HABTM join tables).
- * - `with`: Defines the name of the model for the join table. By default CakePHP
- * will auto-create a model for you. Using the example above it would be called
- * RecipesTag. By using this key you can override this default name. The join
- * table model can be used just like any "regular" model to access the join table directly.
- * - `foreignKey`: the name of the foreign key found in the current model.
- * This is especially handy if you need to define multiple HABTM relationships.
- * The default value for this key is the underscored, singular name of the
- * current model, suffixed with '_id'.
- * - `associationForeignKey`: the name of the foreign key found in the other model.
- * This is especially handy if you need to define multiple HABTM relationships.
- * The default value for this key is the underscored, singular name of the other
- * model, suffixed with '_id'.
- * - `unique`: If true (default value) cake will first delete existing relationship
- * records in the foreign keys table before inserting new ones, when updating a
- * record. So existing associations need to be passed again when updating.
- * To prevent deletion of existing relationship records, set this key to a string 'keepExisting'.
- * - `conditions`: An SQL fragment used to filter related model records. It's good
- * practice to use model names in SQL fragments: "Comment.status = 1" is always
- * better than just "status = 1."
- * - `fields`: A list of fields to be retrieved when the associated model data is
- * fetched. Returns all fields by default.
- * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
- * - `limit`: The maximum number of associated rows you want returned.
- * - `offset`: The number of associated rows to skip over (given the current
- * conditions and order) before fetching and associating.
- * - `finderQuery`, `deleteQuery`, `insertQuery`: A complete SQL query CakePHP
- * can use to fetch, delete, or create new associated model records. This should
- * be used in situations that require very custom results.
- *
- * @var array
- * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm
- */
- public $hasAndBelongsToMany = array();
- /**
- * List of behaviors to load when the model object is initialized. Settings can be
- * passed to behaviors by using the behavior name as index. Eg:
- *
- * public $actsAs = array('Translate', 'MyBehavior' => array('setting1' => 'value1'))
- *
- * @var array
- * @link http://book.cakephp.org/2.0/en/models/behaviors.html#using-behaviors
- */
- public $actsAs = null;
- /**
- * Holds the Behavior objects currently bound to this model.
- *
- * @var BehaviorCollection
- */
- public $Behaviors = null;
- /**
- * Whitelist of fields allowed to be saved.
- *
- * @var array
- */
- public $whitelist = array();
- /**
- * Whether or not to cache sources for this model.
- *
- * @var boolean
- */
- public $cacheSources = true;
- /**
- * Type of find query currently executing.
- *
- * @var string
- */
- public $findQueryType = null;
- /**
- * Number of associations to recurse through during find calls. Fetches only
- * the first level by default.
- *
- * @var integer
- * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive
- */
- public $recursive = 1;
- /**
- * The column name(s) and direction(s) to order find results by default.
- *
- * public $order = "Post.created DESC";
- * public $order = array("Post.view_count DESC", "Post.rating DESC");
- *
- * @var string
- * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#order
- */
- public $order = null;
- /**
- * Array of virtual fields this model has. Virtual fields are aliased
- * SQL expressions. Fields added to this property will be read as other fields in a model
- * but will not be saveable.
- *
- * `public $virtualFields = array('two' => '1 + 1');`
- *
- * Is a simplistic example of how to set virtualFields
- *
- * @var array
- * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#virtualfields
- */
- public $virtualFields = array();
- /**
- * Default list of association keys.
- *
- * @var array
- */
- protected $_associationKeys = array(
- 'belongsTo' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'counterCache'),
- 'hasOne' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'dependent'),
- 'hasMany' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'dependent', 'exclusive', 'finderQuery', 'counterQuery'),
- 'hasAndBelongsToMany' => array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery')
- );
- /**
- * Holds provided/generated association key names and other data for all associations.
- *
- * @var array
- */
- protected $_associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
- /**
- * Holds model associations temporarily to allow for dynamic (un)binding.
- *
- * @var array
- */
- public $__backAssociation = array();
- /**
- * Back inner association
- *
- * @var array
- */
- public $__backInnerAssociation = array();
- /**
- * Back original association
- *
- * @var array
- */
- public $__backOriginalAssociation = array();
- /**
- * Back containable association
- *
- * @var array
- */
- public $__backContainableAssociation = array();
- /**
- * The ID of the model record that was last inserted.
- *
- * @var integer
- */
- protected $_insertID = null;
- /**
- * Has the datasource been configured.
- *
- * @var boolean
- * @see Model::getDataSource
- */
- protected $_sourceConfigured = false;
- /**
- * List of valid finder method options, supplied as the first parameter to find().
- *
- * @var array
- */
- public $findMethods = array(
- 'all' => true, 'first' => true, 'count' => true,
- 'neighbors' => true, 'list' => true, 'threaded' => true
- );
- /**
- * Instance of the CakeEventManager this model is using
- * to dispatch inner events.
- *
- * @var CakeEventManager
- */
- protected $_eventManager = null;
- /**
- * Constructor. Binds the model's database table to the object.
- *
- * If `$id` is an array it can be used to pass several options into the model.
- *
- * - id - The id to start the model on.
- * - table - The table to use for this model.
- * - ds - The connection name this model is connected to.
- * - name - The name of the model eg. Post.
- * - alias - The alias of the model, this is used for registering the instance in the `ClassRegistry`.
- * eg. `ParentThread`
- *
- * ### Overriding Model's __construct method.
- *
- * When overriding Model::__construct() be careful to include and pass in all 3 of the
- * arguments to `parent::__construct($id, $table, $ds);`
- *
- * ### Dynamically creating models
- *
- * You can dynamically create model instances using the $id array syntax.
- *
- * {{{
- * $Post = new Model(array('table' => 'posts', 'name' => 'Post', 'ds' => 'connection2'));
- * }}}
- *
- * Would create a model attached to the posts table on connection2. Dynamic model creation is useful
- * when you want a model object that contains no associations or attached behaviors.
- *
- * @param mixed $id Set this ID for this model on startup, can also be an array of options, see above.
- * @param string $table Name of database table to use.
- * @param string $ds DataSource connection name.
- */
- public function __construct($id = false, $table = null, $ds = null) {
- parent::__construct();
- if (is_array($id)) {
- extract(array_merge(
- array(
- 'id' => $this->id, 'table' => $this->useTable, 'ds' => $this->useDbConfig,
- 'name' => $this->name, 'alias' => $this->alias
- ),
- $id
- ));
- }
- if ($this->name === null) {
- $this->name = (isset($name) ? $name : get_class($this));
- }
- if ($this->alias === null) {
- $this->alias = (isset($alias) ? $alias : $this->name);
- }
- if ($this->primaryKey === null) {
- $this->primaryKey = 'id';
- }
- ClassRegistry::addObject($this->alias, $this);
- $this->id = $id;
- unset($id);
- if ($table === false) {
- $this->useTable = false;
- } elseif ($table) {
- $this->useTable = $table;
- }
- if ($ds !== null) {
- $this->useDbConfig = $ds;
- }
- if (is_subclass_of($this, 'AppModel')) {
- $merge = array('actsAs', 'findMethods');
- $parentClass = get_parent_class($this);
- if ($parentClass !== 'AppModel') {
- $this->_mergeVars($merge, $parentClass);
- }
- $this->_mergeVars($merge, 'AppModel');
- }
- $this->_mergeVars(array('findMethods'), 'Model');
- $this->Behaviors = new BehaviorCollection();
- if ($this->useTable !== false) {
- if ($this->useTable === null) {
- $this->useTable = Inflector::tableize($this->name);
- }
- if ($this->displayField == null) {
- unset($this->displayField);
- }
- $this->table = $this->useTable;
- $this->tableToModel[$this->table] = $this->alias;
- } elseif ($this->table === false) {
- $this->table = Inflector::tableize($this->name);
- }
- if ($this->tablePrefix === null) {
- unset($this->tablePrefix);
- }
- $this->_createLinks();
- $this->Behaviors->init($this->alias, $this->actsAs);
- }
- /**
- * Returns a list of all events that will fire in the model during it's lifecycle.
- * You can override this function to add you own listener callbacks
- *
- * @return array
- */
- public function implementedEvents() {
- return array(
- 'Model.beforeFind' => array('callable' => 'beforeFind', 'passParams' => true),
- 'Model.afterFind' => array('callable' => 'afterFind', 'passParams' => true),
- 'Model.beforeValidate' => array('callable' => 'beforeValidate', 'passParams' => true),
- 'Model.beforeSave' => array('callable' => 'beforeSave', 'passParams' => true),
- 'Model.afterSave' => array('callable' => 'afterSave', 'passParams' => true),
- 'Model.beforeDelete' => array('callable' => 'beforeDelete', 'passParams' => true),
- 'Model.afterDelete' => array('callable' => 'afterDelete'),
- );
- }
- /**
- * Returns the CakeEventManager manager instance that is handling any callbacks.
- * You can use this instance to register any new listeners or callbacks to the
- * model events, or create your own events and trigger them at will.
- *
- * @return CakeEventManager
- */
- public function getEventManager() {
- if (empty($this->_eventManager)) {
- $this->_eventManager = new CakeEventManager();
- $this->_eventManager->attach($this->Behaviors);
- $this->_eventManager->attach($this);
- }
- return $this->_eventManager;
- }
- /**
- * Handles custom method calls, like findBy<field> for DB models,
- * and custom RPC calls for remote data sources.
- *
- * @param string $method Name of method to call.
- * @param array $params Parameters for the method.
- * @return mixed Whatever is returned by called method
- */
- public function __call($method, $params) {
- $result = $this->Behaviors->dispatchMethod($this, $method, $params);
- if ($result !== array('unhandled')) {
- return $result;
- }
- $return = $this->getDataSource()->query($method, $params, $this);
- return $return;
- }
- /**
- * Handles the lazy loading of model associations by looking in the association arrays for the requested variable
- *
- * @param string $name variable tested for existence in class
- * @return boolean true if the variable exists (if is a not loaded model association it will be created), false otherwise
- */
- public function __isset($name) {
- $className = false;
- foreach ($this->_associations as $type) {
- if (isset($name, $this->{$type}[$name])) {
- $className = empty($this->{$type}[$name]['className']) ? $name : $this->{$type}[$name]['className'];
- break;
- } elseif (isset($name, $this->__backAssociation[$type][$name])) {
- $className = empty($this->__backAssociation[$type][$name]['className']) ?
- $name : $this->__backAssociation[$type][$name]['className'];
- break;
- } elseif ($type == 'hasAndBelongsToMany') {
- foreach ($this->{$type} as $k => $relation) {
- if (empty($relation['with'])) {
- continue;
- }
- if (is_array($relation['with'])) {
- if (key($relation['with']) === $name) {
- $className = $name;
- }
- } else {
- list($plugin, $class) = pluginSplit($relation['with']);
- if ($class === $name) {
- $className = $relation['with'];
- }
- }
- if ($className) {
- $assocKey = $k;
- $dynamic = !empty($relation['dynamicWith']);
- break(2);
- }
- }
- }
- }
- if (!$className) {
- return false;
- }
- list($plugin, $className) = pluginSplit($className);
- if (!ClassRegistry::isKeySet($className) && !empty($dynamic)) {
- $this->{$className} = new AppModel(array(
- 'name' => $className,
- 'table' => $this->hasAndBelongsToMany[$assocKey]['joinTable'],
- 'ds' => $this->useDbConfig
- ));
- } else {
- $this->_constructLinkedModel($name, $className, $plugin);
- }
- if (!empty($assocKey)) {
- $this->hasAndBelongsToMany[$assocKey]['joinTable'] = $this->{$name}->table;
- if (count($this->{$name}->schema()) <= 2 && $this->{$name}->primaryKey !== false) {
- $this->{$name}->primaryKey = $this->hasAndBelongsToMany[$assocKey]['foreignKey'];
- }
- }
- return true;
- }
- /**
- * Returns the value of the requested variable if it can be set by __isset()
- *
- * @param string $name variable requested for it's value or reference
- * @return mixed value of requested variable if it is set
- */
- public function __get($name) {
- if ($name === 'displayField') {
- return $this->displayField = $this->hasField(array('title', 'name', $this->primaryKey));
- }
- if ($name === 'tablePrefix') {
- $this->setDataSource();
- if (property_exists($this, 'tablePrefix') && !empty($this->tablePrefix)) {
- return $this->tablePrefix;
- }
- return $this->tablePrefix = null;
- }
- if (isset($this->{$name})) {
- return $this->{$name};
- }
- }
- /**
- * Bind model associations on the fly.
- *
- * If `$reset` is false, association will not be reset
- * to the originals defined in the model
- *
- * Example: Add a new hasOne binding to the Profile model not
- * defined in the model source code:
- *
- * `$this->User->bindModel( array('hasOne' => array('Profile')) );`
- *
- * Bindings that are not made permanent will be reset by the next Model::find() call on this
- * model.
- *
- * @param array $params Set of bindings (indexed by binding type)
- * @param boolean $reset Set to false to make the binding permanent
- * @return boolean Success
- * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
- */
- public function bindModel($params, $reset = true) {
- foreach ($params as $assoc => $model) {
- if ($reset === true && !isset($this->__backAssociation[$assoc])) {
- $this->__backAssociation[$assoc] = $this->{$assoc};
- }
- foreach ($model as $key => $value) {
- $assocName = $key;
- if (is_numeric($key)) {
- $assocName = $value;
- $value = array();
- }
- $this->{$assoc}[$assocName] = $value;
- if (property_exists($this, $assocName)) {
- unset($this->{$assocName});
- }
- if ($reset === false && isset($this->__backAssociation[$assoc])) {
- $this->__backAssociation[$assoc][$assocName] = $value;
- }
- }
- }
- $this->_createLinks();
- return true;
- }
- /**
- * Turn off associations on the fly.
- *
- * If $reset is false, association will not be reset
- * to the originals defined in the model
- *
- * Example: Turn off the associated Model Support request,
- * to temporarily lighten the User model:
- *
- * `$this->User->unbindModel( array('hasMany' => array('Supportrequest')) );`
- *
- * unbound models that are not made permanent will reset with the next call to Model::find()
- *
- * @param array $params Set of bindings to unbind (indexed by binding type)
- * @param boolean $reset Set to false to make the unbinding permanent
- * @return boolean Success
- * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
- */
- public function unbindModel($params, $reset = true) {
- foreach ($params as $assoc => $models) {
- if ($reset === true && !isset($this->__backAssociation[$assoc])) {
- $this->__backAssociation[$assoc] = $this->{$assoc};
- }
- foreach ($models as $model) {
- if ($reset === false && isset($this->__backAssociation[$assoc][$model])) {
- unset($this->__backAssociation[$assoc][$model]);
- }
- unset($this->{$assoc}[$model]);
- }
- }
- return true;
- }
- /**
- * Create a set of associations.
- *
- * @return void
- */
- protected function _createLinks() {
- foreach ($this->_associations as $type) {
- if (!is_array($this->{$type})) {
- $this->{$type} = explode(',', $this->{$type});
- foreach ($this->{$type} as $i => $className) {
- $className = trim($className);
- unset ($this->{$type}[$i]);
- $this->{$type}[$className] = array();
- }
- }
- if (!empty($this->{$type})) {
- foreach ($this->{$type} as $assoc => $value) {
- $plugin = null;
- if (is_numeric($assoc)) {
- unset ($this->{$type}[$assoc]);
- $assoc = $value;
- $value = array();
- if (strpos($assoc, '.') !== false) {
- list($plugin, $assoc) = pluginSplit($assoc);
- $this->{$type}[$assoc] = array('className' => $plugin . '.' . $assoc);
- } else {
- $this->{$type}[$assoc] = $value;
- }
- }
- $this->_generateAssociation($type, $assoc);
- }
- }
- }
- }
- /**
- * Protected helper method to create associated models of a given class.
- *
- * @param string $assoc Association name
- * @param string $className Class name
- * @param string $plugin name of the plugin where $className is located
- * examples: public $hasMany = array('Assoc' => array('className' => 'ModelName'));
- * usage: $this->Assoc->modelMethods();
- *
- * public $hasMany = array('ModelName');
- * usage: $this->ModelName->modelMethods();
- * @return void
- */
- protected function _constructLinkedModel($assoc, $className = null, $plugin = null) {
- if (empty($className)) {
- $className = $assoc;
- }
- if (!isset($this->{$assoc}) || $this->{$assoc}->name !== $className) {
- if ($plugin) {
- $plugin .= '.';
- }
- $model = array('class' => $plugin . $className, 'alias' => $assoc);
- $this->{$assoc} = ClassRegistry::init($model);
- if ($plugin) {
- ClassRegistry::addObject($plugin . $className, $this->{$assoc});
- }
- if ($assoc) {
- $this->tableToModel[$this->{$assoc}->table] = $assoc;
- }
- }
- }
- /**
- * Build an array-based association from string.
- *
- * @param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
- * @param string $assocKey
- * @return void
- */
- protected function _generateAssociation($type, $assocKey) {
- $class = $assocKey;
- $dynamicWith = false;
- foreach ($this->_associationKeys[$type] as $key) {
- if (!isset($this->{$type}[$assocKey][$key]) || $this->{$type}[$assocKey][$key] === null) {
- $data = '';
- switch ($key) {
- case 'fields':
- $data = '';
- break;
- case 'foreignKey':
- $data = (($type == 'belongsTo') ? Inflector::underscore($assocKey) : Inflector::singularize($this->table)) . '_id';
- break;
- case 'associationForeignKey':
- $data = Inflector::singularize($this->{$class}->table) . '_id';
- break;
- case 'with':
- $data = Inflector::camelize(Inflector::singularize($this->{$type}[$assocKey]['joinTable']));
- $dynamicWith = true;
- break;
- case 'joinTable':
- $tables = array($this->table, $this->{$class}->table);
- sort ($tables);
- $data = $tables[0] . '_' . $tables[1];
- break;
- case 'className':
- $data = $class;
- break;
- case 'unique':
- $data = true;
- break;
- }
- $this->{$type}[$assocKey][$key] = $data;
- }
- if ($dynamicWith) {
- $this->{$type}[$assocKey]['dynamicWith'] = true;
- }
- }
- }
- /**
- * Sets a custom table for your controller class. Used by your controller to select a database table.
- *
- * @param string $tableName Name of the custom table
- * @throws MissingTableException when database table $tableName is not found on data source
- * @return void
- */
- public function setSource($tableName) {
- $this->setDataSource($this->useDbConfig);
- $db = ConnectionManager::getDataSource($this->useDbConfig);
- $db->cacheSources = ($this->cacheSources && $db->cacheSources);
- if (method_exists($db, 'listSources')) {
- $sources = $db->listSources();
- if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) {
- throw new MissingTableException(array(
- 'table' => $this->tablePrefix . $tableName,
- 'class' => $this->alias,
- 'ds' => $this->useDbConfig,
- ));
- }
- $this->_schema = null;
- }
- $this->table = $this->useTable = $tableName;
- $this->tableToModel[$this->table] = $this->alias;
- }
- /**
- * This function does two things:
- *
- * 1. it scans the array $one for the primary key,
- * and if that's found, it sets the current id to the value of $one[id].
- * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object.
- * 2. Returns an array with all of $one's keys and values.
- * (Alternative indata: two strings, which are mangled to
- * a one-item, two-dimensional array using $one for a key and $two as its value.)
- *
- * @param mixed $one Array or string of data
- * @param string $two Value string for the alternative indata method
- * @return array Data with all of $one's keys and values
- * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html
- */
- public function set($one, $two = null) {
- if (!$one) {
- return;
- }
- if (is_object($one)) {
- if ($one instanceof SimpleXMLElement || $one instanceof DOMNode) {
- $one = $this->_normalizeXmlData(Xml::toArray($one));
- } else {
- $one = Set::reverse($one);
- }
- }
- if (is_array($one)) {
- $data = $one;
- if (empty($one[$this->alias])) {
- $data = $this->_setAliasData($one);
- }
- } else {
- $data = array($this->alias => array($one => $two));
- }
- foreach ($data as $modelName => $fieldSet) {
- if (is_array($fieldSet)) {
- foreach ($fieldSet as $fieldName => $fieldValue) {
- if (isset($this->validationErrors[$fieldName])) {
- unset ($this->validationErrors[$fieldName]);
- }
- if ($modelName === $this->alias) {
- if ($fieldName === $this->primaryKey) {
- $this->id = $fieldValue;
- }
- }
- if (is_array($fieldValue) || is_object($fieldValue)) {
- $fieldValue = $this->deconstruct($fieldName, $fieldValue);
- }
- $this->data[$modelName][$fieldName] = $fieldValue;
- }
- }
- }
- return $data;
- }
- /**
- * Move values to alias
- *
- * @param array $data
- * @return array
- */
- protected function _setAliasData($data) {
- $models = array_keys($this->getAssociated());
- $schema = array_keys($this->schema());
- foreach ($data as $field => $value) {
- if (in_array($field, $schema) || !in_array($field, $models)) {
- $data[$this->alias][$field] = $value;
- unset($data[$field]);
- }
- }
- return $data;
- }
- /**
- * Normalize Xml::toArray() to use in Model::save()
- *
- * @param array $xml XML as array
- * @return array
- */
- protected function _normalizeXmlData(array $xml) {
- $return = array();
- foreach ($xml as $key => $value) {
- if (is_array($value)) {
- $return[Inflector::camelize($key)] = $this->_normalizeXmlData($value);
- } elseif ($key[0] === '@') {
- $return[substr($key, 1)] = $value;
- } else {
- $return[$key] = $value;
- }
- }
- return $return;
- }
- /**
- * Deconstructs a complex data type (array or object) into a single field value.
- *
- * @param string $field The name of the field to be deconstructed
- * @param mixed $data An array or object to be deconstructed into a field
- * @return mixed The resulting data that should be assigned to a field
- */
- public function deconstruct($field, $data) {
- if (!is_array($data)) {
- return $data;
- }
- $type = $this->getColumnType($field);
- if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
- $useNewDate = (isset($data['year']) || isset($data['month']) ||
- isset($data['day']) || isset($data['hour']) || isset($data['minute']));
- $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
- $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
- $date = array();
- if (isset($data['meridian']) && empty($data['meridian'])) {
- return null;
- }
- if (
- isset($data['hour']) &&
- isset($data['meridian']) &&
- !empty($data['hour']) &&
- $data['hour'] != 12 &&
- 'pm' == $data['meridian']
- ) {
- $data['hour'] = $data['hour'] + 12;
- }
- if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
- $data['hour'] = '00';
- }
- if ($type == 'time') {
- foreach ($timeFields as $key => $val) {
- if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
- $data[$val] = '00';
- } elseif ($data[$val] !== '') {
- $data[$val] = sprintf('%02d', $data[$val]);
- }
- if (!empty($data[$val])) {
- $date[$key] = $data[$val];
- } else {
- return null;
- }
- }
- }
- if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
- foreach ($dateFields as $key => $val) {
- if ($val == 'hour' || $val == 'min' || $val == 'sec') {
- if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
- $data[$val] = '00';
- } else {
- $data[$val] = sprintf('%02d', $data[$val]);
- }
- }
- if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
- return null;
- }
- if (isset($data[$val]) && !empty($data[$val])) {
- $date[$key] = $data[$val];
- }
- }
- }
- if ($useNewDate && !empty($date)) {
- $format = $this->getDataSource()->columns[$type]['format'];
- foreach (array('m', 'd', 'H', 'i', 's') as $index) {
- if (isset($date[$index])) {
- $date[$index] = sprintf('%02d', $date[$index]);
- }
- }
- return str_replace(array_keys($date), array_values($date), $format);
- }
- }
- return $data;
- }
- /**
- * Returns an array of table metadata (column names and types) from the database.
- * $field => keys(type, null, default, key, length, extra)
- *
- * @param mixed $field Set to true to reload schema, or a string to return a specific field
- * @return array Array of table metadata
- */
- public function schema($field = false) {
- if ($this->useTable !== false && (!is_array($this->_schema) || $field === true)) {
- $db = $this->getDataSource();
- $db->cacheSources = ($this->cacheSources && $db->cacheSources);
- if (method_exists($db, 'describe') && $this->useTable !== false) {
- $this->_schema = $db->describe($this);
- } elseif ($this->useTable === false) {
- $this->_schema = array();
- }
- }
- if (is_string($field)) {
- if (isset($this->_schema[$field])) {
- return $this->_schema[$field];
- } else {
- return null;
- }
- }
- return $this->_schema;
- }
- /**
- * Returns an associative array of field names and column types.
- *
- * @return array Field types indexed by field name
- */
- public function getColumnTypes() {
- $columns = $this->schema();
- if (empty($columns)) {
- trigger_error(__d('cake_dev', '(Model::getColumnTypes) Unable to build model field data. If you are using a model without a database table, try implementing schema()'), E_USER_WARNING);
- }
- $cols = array();
- foreach ($columns as $field => $values) {
- $cols[$field] = $values['type'];
- }
- return $cols;
- }
- /**
- * Returns the column type of a column in the model.
- *
- * @param string $column The name of the model column
- * @return string Column type
- */
- public function getColumnType($column) {
- $db = $this->getDataSource();
- $cols = $this->schema();
- $model = null;
- $startQuote = isset($db->startQuote) ? $db->startQuote : null;
- $endQuote = isset($db->endQuote) ? $db->endQuote : null;
- $column = str_replace(array($startQuote, $endQuote), '', $column);
- if (strpos($column, '.')) {
- list($model, $column) = explode('.', $column);
- }
- if ($model != $this->alias && isset($this->{$model})) {
- return $this->{$model}->getColumnType($column);
- }
- if (isset($cols[$column]) && isset($cols[$column]['type'])) {
- return $cols[$column]['type'];
- }
- return null;
- }
- /**
- * Returns true if the supplied field exists in the model's database table.
- *
- * @param mixed $name Name of field to look for, or an array of names
- * @param boolean $checkVirtual checks if the field is declared as virtual
- * @return mixed If $name is a string, returns a boolean indicating whether the field exists.
- * If $name is an array of field names, returns the first field that exists,
- * or false if none exist.
- */
- public function hasField($name, $checkVirtual = false) {
- if (is_array($name)) {
- foreach ($name as $n) {
- if ($this->hasField($n, $checkVirtual)) {
- return $n;
- }
- }
- return false;
- }
- if ($checkVirtual && !empty($this->virtualFields)) {
- if ($this->isVirtualField($name)) {
- return true;
- }
- }
- if (empty($this->_schema)) {
- $this->schema();
- }
- if ($this->_schema != null) {
- return isset($this->_schema[$name]);
- }
- return false;
- }
- /**
- * Check that a method is callable on a model. This will check both the model's own methods, its
- * inherited methods and methods that could be callable through behaviors.
- *
- * @param string $method The method to be called.
- * @return boolean True on method being callable.
- */
- public function hasMethod($method) {
- if (method_exists($this, $method)) {
- return true;
- }
- if ($this->Behaviors->hasMethod($method)) {
- return true;
- }
- return false;
- }
- /**
- * Returns true if the supplied field is a model Virtual Field
- *
- * @param string $field Name of field to look for
- * @return boolean indicating whether the field exists as a model virtual field.
- */
- public function isVirtualField($field) {
- if (empty($this->virtualFields) || !is_string($field)) {
- return false;
- }
- if (isset($this->virtualFields[$field])) {
- return true;
- }
- if (strpos($field, '.') !== false) {
- list($model, $field) = explode('.', $field);
- if ($model == $this->alias && isset($this->virtualFields[$field])) {
- return true;
- }
- }
- return false;
- }
- /**
- * Returns the expression for a model virtual field
- *
- * @param string $field Name of field to look for
- * @return mixed If $field is string expression bound to virtual field $field
- * If $field is null, returns an array of all model virtual fields
- * or false if none $field exist.
- */
- public function getVirtualField($field = null) {
- if ($field == null) {
- return empty($this->virtualFields) ? false : $this->virtualFields;
- }
- if ($this->isVirtualField($field)) {
- if (strpos($field, '.') !== false) {
- list($model, $field) = explode('.', $field);
- }
- return $this->virtualFields[$field];
- }
- return false;
- }
- /**
- * Initializes the model for writing a new record, loading the default values
- * for those fields that are not defined in $data, and clearing previous validation errors.
- * Especially helpful for saving data in loops.
- *
- * @param mixed $data Optional data array to assign to the model after it is created. If null or false,
- * schema data defaults are not merged.
- * @param boolean $filterKey If true, overwrites any primary key input with an empty value
- * @return array The current Model::data; after merging $data and/or defaults from database
- * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-create-array-data-array
- */
- public function create($data = array(), $filterKey = false) {
- $defaults = array();
- $this->id = false;
- $this->data = array();
- $this->validationErrors = array();
- if ($data !== null && $data !== false) {
- foreach ($this->schema() as $field => $properties) {
- if ($this->primaryKey !== $field && isset($properties['default']) && $properties['default'] !== '') {
- $defaults[$field] = $properties['default'];
- }
- }
- $this->set($defaults);
- $this->set($data);
- }
- if ($filterKey) {
- $this->set($this->primaryKey, false);
- }
- return $this->data;
- }
- /**
- * Returns a list of fields from the database, and sets the current model
- * data (Model::$data) with the record found.
- *
- * @param mixed $fields String of single field name, or an array of field names.
- * @param mixed $id The ID of the record to read
- * @return array Array of database fields, or false if not found
- * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-read
- */
- public function read($fields = null, $id = null) {
- $this->validationErrors = array();
- if ($id != null) {
- $this->id = $id;
- }
- $id = $this->id;
- if (is_array($this->id)) {
- $id = $this->id[0];
- }
- if ($id !== null && $id !== false) {
- $this->data = $this->find('first', array(
- 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
- 'fields' => $fields
- ));
- return $this->data;
- } else {
- return false;
- }
- }
- /**
- * Returns the contents of a single field given the supplied conditions, in the
- * supplied order.
- *
- * @param string $name Name of field to get
- * @param array $conditions SQL conditions (defaults to NULL)
- * @param string $order SQL ORDER BY fragment
- * @return string field contents, or false if not found
- * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-field
- */
- public function field($name, $conditions = null, $order = null) {
- if ($conditions === null && $this->id !== false) {
- $conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
- }
- if ($this->recursive >= 1) {
- $recursive = -1;
- } else {
- $recursive = $this->recursive;
- }
- $fields = $name;
- if ($data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'))) {
- if (strpos($name, '.') === false) {
- if (isset($data[$this->alias][$name])) {
- return $data[$this->alias][$name];
- }
- } else {
- $name = explode('.', $name);
- if (isset($data[$name[0]][$name[1]])) {
- return $data[$name[0]][$name[1]];
- }
- }
- if (isset($data[0]) && count($data[0]) > 0) {
- return array_shift($data[0]);
- }
- } else {
- return false;
- }
- }
- /**
- * Saves the value of a single field to the database, based on the current
- * model ID.
- *
- * @param string $name Name of the table field
- * @param mixed $value Value of the field
- * @param array $validate See $options param in Model::save(). Does not respect 'fieldList' key if passed
- * @return boolean See Model::save()
- * @see Model::save()
- * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savefield-string-fieldname-string-fieldvalue-validate-false
- */
- public function saveField($name, $value, $validate = false) {
- $id = $this->id;
- $this->create(false);
- if (is_array($validate)) {
- $options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate);
- } else {
- $options = array('validate' => $validate, 'fieldList' => array($name));
- }
- return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options);
- }
- /**
- * Saves model data (based on white-list, if supplied) to the database. By
- * default, validation occurs before save.
- *
- * @param array $data Data to save.
- * @param mixed $validate Either a boolean, or an array.
- * If a boolean, indicates whether or not to validate before saving.
- * If an array, allows control of validate, callbacks, and fieldList
- * @param array $fieldList List of fields to allow to be written
- * @return mixed On success Model::$data if its not empty or true, false on failure
- * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html
- */
- public function save($data = null, $validate = true, $fieldList = array()) {
- $defaults = array('validate' => true, 'fieldList' => array(), 'callbacks' => true);
- $_whitelist = $this->whitelist;
- $fields = array();
- if (!is_array($validate)) {
- $options = array_merge($defa…
Large files files are truncated, but you can click here to view the full file