PageRenderTime 59ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/Cake/Model/Model.php

https://gitlab.com/fouzia23chowdhury/cakephpCRUD
PHP | 3883 lines | 1928 code | 489 blank | 1466 comment | 504 complexity | 66efde92926a0479f9d0e591834a8a49 MD5 | raw file

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

  1. <?php
  2. /**
  3. * Object-relational mapper.
  4. *
  5. * DBO-backed object data model, for mapping database tables to CakePHP objects.
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * For full copyright and license information, please see the LICENSE.txt
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  15. * @link http://cakephp.org CakePHP(tm) Project
  16. * @package Cake.Model
  17. * @since CakePHP(tm) v 0.10.0.0
  18. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  19. */
  20. App::uses('ClassRegistry', 'Utility');
  21. App::uses('Validation', 'Utility');
  22. App::uses('String', 'Utility');
  23. App::uses('Hash', 'Utility');
  24. App::uses('BehaviorCollection', 'Model');
  25. App::uses('ModelBehavior', 'Model');
  26. App::uses('ModelValidator', 'Model');
  27. App::uses('ConnectionManager', 'Model');
  28. App::uses('Xml', 'Utility');
  29. App::uses('CakeEvent', 'Event');
  30. App::uses('CakeEventListener', 'Event');
  31. App::uses('CakeEventManager', 'Event');
  32. /**
  33. * Object-relational mapper.
  34. *
  35. * DBO-backed object data model.
  36. * Automatically selects a database table name based on a pluralized lowercase object class name
  37. * (i.e. class 'User' => table 'users'; class 'Man' => table 'men')
  38. * The table is required to have at least 'id auto_increment' primary key.
  39. *
  40. * @package Cake.Model
  41. * @link http://book.cakephp.org/2.0/en/models.html
  42. */
  43. class Model extends Object implements CakeEventListener {
  44. /**
  45. * The name of the DataSource connection that this Model uses
  46. *
  47. * The value must be an attribute name that you defined in `app/Config/database.php`
  48. * or created using `ConnectionManager::create()`.
  49. *
  50. * @var string
  51. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#usedbconfig
  52. */
  53. public $useDbConfig = 'default';
  54. /**
  55. * Custom database table name, or null/false if no table association is desired.
  56. *
  57. * @var string
  58. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#usetable
  59. */
  60. public $useTable = null;
  61. /**
  62. * Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements.
  63. *
  64. * This field is also used in `find('list')` when called with no extra parameters in the fields list
  65. *
  66. * @var string
  67. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#displayfield
  68. */
  69. public $displayField = null;
  70. /**
  71. * Value of the primary key ID of the record that this model is currently pointing to.
  72. * Automatically set after database insertions.
  73. *
  74. * @var mixed
  75. */
  76. public $id = false;
  77. /**
  78. * Container for the data that this model gets from persistent storage (usually, a database).
  79. *
  80. * @var array
  81. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#data
  82. */
  83. public $data = array();
  84. /**
  85. * Holds physical schema/database name for this model. Automatically set during Model creation.
  86. *
  87. * @var string
  88. */
  89. public $schemaName = null;
  90. /**
  91. * Table name for this Model.
  92. *
  93. * @var string
  94. */
  95. public $table = false;
  96. /**
  97. * The name of the primary key field for this model.
  98. *
  99. * @var string
  100. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#primarykey
  101. */
  102. public $primaryKey = null;
  103. /**
  104. * Field-by-field table metadata.
  105. *
  106. * @var array
  107. */
  108. protected $_schema = null;
  109. /**
  110. * List of validation rules. It must be an array with the field name as key and using
  111. * as value one of the following possibilities
  112. *
  113. * ### Validating using regular expressions
  114. *
  115. * ```
  116. * public $validate = array(
  117. * 'name' => '/^[a-z].+$/i'
  118. * );
  119. * ```
  120. *
  121. * ### Validating using methods (no parameters)
  122. *
  123. * ```
  124. * public $validate = array(
  125. * 'name' => 'notEmpty'
  126. * );
  127. * ```
  128. *
  129. * ### Validating using methods (with parameters)
  130. *
  131. * ```
  132. * public $validate = array(
  133. * 'length' => array(
  134. * 'rule' => array('lengthBetween', 5, 25)
  135. * )
  136. * );
  137. * ```
  138. *
  139. * ### Validating using custom method
  140. *
  141. * ```
  142. * public $validate = array(
  143. * 'password' => array(
  144. * 'rule' => array('customValidation')
  145. * )
  146. * );
  147. * public function customValidation($data) {
  148. * // $data will contain array('password' => 'value')
  149. * if (isset($this->data[$this->alias]['password2'])) {
  150. * return $this->data[$this->alias]['password2'] === current($data);
  151. * }
  152. * return true;
  153. * }
  154. * ```
  155. *
  156. * ### Validations with messages
  157. *
  158. * The messages will be used in Model::$validationErrors and can be used in the FormHelper
  159. *
  160. * ```
  161. * public $validate = array(
  162. * 'length' => array(
  163. * 'rule' => array('lengthBetween', 5, 15),
  164. * 'message' => array('Between %d to %d characters')
  165. * )
  166. * );
  167. * ```
  168. *
  169. * ### Multiple validations to the same field
  170. *
  171. * ```
  172. * public $validate = array(
  173. * 'login' => array(
  174. * array(
  175. * 'rule' => 'alphaNumeric',
  176. * 'message' => 'Only alphabets and numbers allowed',
  177. * 'last' => true
  178. * ),
  179. * array(
  180. * 'rule' => array('minLength', 8),
  181. * 'message' => array('Minimum length of %d characters')
  182. * )
  183. * )
  184. * );
  185. * ```
  186. *
  187. * ### Valid keys in validations
  188. *
  189. * - `rule`: String with method name, regular expression (started by slash) or array with method and parameters
  190. * - `message`: String with the message or array if have multiple parameters. See http://php.net/sprintf
  191. * - `last`: Boolean value to indicate if continue validating the others rules if the current fail [Default: true]
  192. * - `required`: Boolean value to indicate if the field must be present on save
  193. * - `allowEmpty`: Boolean value to indicate if the field can be empty
  194. * - `on`: Possible values: `update`, `create`. Indicate to apply this rule only on update or create
  195. *
  196. * @var array
  197. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#validate
  198. * @link http://book.cakephp.org/2.0/en/models/data-validation.html
  199. */
  200. public $validate = array();
  201. /**
  202. * List of validation errors.
  203. *
  204. * @var array
  205. */
  206. public $validationErrors = array();
  207. /**
  208. * Name of the validation string domain to use when translating validation errors.
  209. *
  210. * @var string
  211. */
  212. public $validationDomain = null;
  213. /**
  214. * Database table prefix for tables in model.
  215. *
  216. * @var string
  217. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#tableprefix
  218. */
  219. public $tablePrefix = null;
  220. /**
  221. * Plugin model belongs to.
  222. *
  223. * @var string
  224. */
  225. public $plugin = null;
  226. /**
  227. * Name of the model.
  228. *
  229. * @var string
  230. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#name
  231. */
  232. public $name = null;
  233. /**
  234. * Alias name for model.
  235. *
  236. * @var string
  237. */
  238. public $alias = null;
  239. /**
  240. * List of table names included in the model description. Used for associations.
  241. *
  242. * @var array
  243. */
  244. public $tableToModel = array();
  245. /**
  246. * Whether or not to cache queries for this model. This enables in-memory
  247. * caching only, the results are not stored beyond the current request.
  248. *
  249. * @var bool
  250. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#cachequeries
  251. */
  252. public $cacheQueries = false;
  253. /**
  254. * Detailed list of belongsTo associations.
  255. *
  256. * ### Basic usage
  257. *
  258. * `public $belongsTo = array('Group', 'Department');`
  259. *
  260. * ### Detailed configuration
  261. *
  262. * ```
  263. * public $belongsTo = array(
  264. * 'Group',
  265. * 'Department' => array(
  266. * 'className' => 'Department',
  267. * 'foreignKey' => 'department_id'
  268. * )
  269. * );
  270. * ```
  271. *
  272. * ### Possible keys in association
  273. *
  274. * - `className`: the class name of the model being associated to the current model.
  275. * If you're defining a 'Profile belongsTo User' relationship, the className key should equal 'User.'
  276. * - `foreignKey`: the name of the foreign key found in the current model. This is
  277. * especially handy if you need to define multiple belongsTo relationships. The default
  278. * value for this key is the underscored, singular name of the other model, suffixed with '_id'.
  279. * - `conditions`: An SQL fragment used to filter related model records. It's good
  280. * practice to use model names in SQL fragments: 'User.active = 1' is always
  281. * better than just 'active = 1.'
  282. * - `type`: the type of the join to use in the SQL query, default is LEFT which
  283. * may not fit your needs in all situations, INNER may be helpful when you want
  284. * everything from your main and associated models or nothing at all!(effective
  285. * when used with some conditions of course). (NB: type value is in lower case - i.e. left, inner)
  286. * - `fields`: A list of fields to be retrieved when the associated model data is
  287. * fetched. Returns all fields by default.
  288. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
  289. * - `counterCache`: If set to true the associated Model will automatically increase or
  290. * decrease the "[singular_model_name]_count" field in the foreign table whenever you do
  291. * a save() or delete(). If its a string then its the field name to use. The value in the
  292. * counter field represents the number of related rows.
  293. * - `counterScope`: Optional conditions array to use for updating counter cache field.
  294. *
  295. * @var array
  296. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#belongsto
  297. */
  298. public $belongsTo = array();
  299. /**
  300. * Detailed list of hasOne associations.
  301. *
  302. * ### Basic usage
  303. *
  304. * `public $hasOne = array('Profile', 'Address');`
  305. *
  306. * ### Detailed configuration
  307. *
  308. * ```
  309. * public $hasOne = array(
  310. * 'Profile',
  311. * 'Address' => array(
  312. * 'className' => 'Address',
  313. * 'foreignKey' => 'user_id'
  314. * )
  315. * );
  316. * ```
  317. *
  318. * ### Possible keys in association
  319. *
  320. * - `className`: the class name of the model being associated to the current model.
  321. * If you're defining a 'User hasOne Profile' relationship, the className key should equal 'Profile.'
  322. * - `foreignKey`: the name of the foreign key found in the other model. This is
  323. * especially handy if you need to define multiple hasOne relationships.
  324. * The default value for this key is the underscored, singular name of the
  325. * current model, suffixed with '_id'. In the example above it would default to 'user_id'.
  326. * - `conditions`: An SQL fragment used to filter related model records. It's good
  327. * practice to use model names in SQL fragments: "Profile.approved = 1" is
  328. * always better than just "approved = 1."
  329. * - `fields`: A list of fields to be retrieved when the associated model data is
  330. * fetched. Returns all fields by default.
  331. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
  332. * - `dependent`: When the dependent key is set to true, and the model's delete()
  333. * method is called with the cascade parameter set to true, associated model
  334. * records are also deleted. In this case we set it true so that deleting a
  335. * User will also delete her associated Profile.
  336. *
  337. * @var array
  338. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasone
  339. */
  340. public $hasOne = array();
  341. /**
  342. * Detailed list of hasMany associations.
  343. *
  344. * ### Basic usage
  345. *
  346. * `public $hasMany = array('Comment', 'Task');`
  347. *
  348. * ### Detailed configuration
  349. *
  350. * ```
  351. * public $hasMany = array(
  352. * 'Comment',
  353. * 'Task' => array(
  354. * 'className' => 'Task',
  355. * 'foreignKey' => 'user_id'
  356. * )
  357. * );
  358. * ```
  359. *
  360. * ### Possible keys in association
  361. *
  362. * - `className`: the class name of the model being associated to the current model.
  363. * If you're defining a 'User hasMany Comment' relationship, the className key should equal 'Comment.'
  364. * - `foreignKey`: the name of the foreign key found in the other model. This is
  365. * especially handy if you need to define multiple hasMany relationships. The default
  366. * value for this key is the underscored, singular name of the actual model, suffixed with '_id'.
  367. * - `conditions`: An SQL fragment used to filter related model records. It's good
  368. * practice to use model names in SQL fragments: "Comment.status = 1" is always
  369. * better than just "status = 1."
  370. * - `fields`: A list of fields to be retrieved when the associated model data is
  371. * fetched. Returns all fields by default.
  372. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
  373. * - `limit`: The maximum number of associated rows you want returned.
  374. * - `offset`: The number of associated rows to skip over (given the current
  375. * conditions and order) before fetching and associating.
  376. * - `dependent`: When dependent is set to true, recursive model deletion is
  377. * possible. In this example, Comment records will be deleted when their
  378. * associated User record has been deleted.
  379. * - `exclusive`: When exclusive is set to true, recursive model deletion does
  380. * the delete with a deleteAll() call, instead of deleting each entity separately.
  381. * This greatly improves performance, but may not be ideal for all circumstances.
  382. * - `finderQuery`: A complete SQL query CakePHP can use to fetch associated model
  383. * records. This should be used in situations that require very custom results.
  384. *
  385. * @var array
  386. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany
  387. */
  388. public $hasMany = array();
  389. /**
  390. * Detailed list of hasAndBelongsToMany associations.
  391. *
  392. * ### Basic usage
  393. *
  394. * `public $hasAndBelongsToMany = array('Role', 'Address');`
  395. *
  396. * ### Detailed configuration
  397. *
  398. * ```
  399. * public $hasAndBelongsToMany = array(
  400. * 'Role',
  401. * 'Address' => array(
  402. * 'className' => 'Address',
  403. * 'foreignKey' => 'user_id',
  404. * 'associationForeignKey' => 'address_id',
  405. * 'joinTable' => 'addresses_users'
  406. * )
  407. * );
  408. * ```
  409. *
  410. * ### Possible keys in association
  411. *
  412. * - `className`: the class name of the model being associated to the current model.
  413. * If you're defining a 'Recipe HABTM Tag' relationship, the className key should equal 'Tag.'
  414. * - `joinTable`: The name of the join table used in this association (if the
  415. * current table doesn't adhere to the naming convention for HABTM join tables).
  416. * - `with`: Defines the name of the model for the join table. By default CakePHP
  417. * will auto-create a model for you. Using the example above it would be called
  418. * RecipesTag. By using this key you can override this default name. The join
  419. * table model can be used just like any "regular" model to access the join table directly.
  420. * - `foreignKey`: the name of the foreign key found in the current model.
  421. * This is especially handy if you need to define multiple HABTM relationships.
  422. * The default value for this key is the underscored, singular name of the
  423. * current model, suffixed with '_id'.
  424. * - `associationForeignKey`: the name of the foreign key found in the other model.
  425. * This is especially handy if you need to define multiple HABTM relationships.
  426. * The default value for this key is the underscored, singular name of the other
  427. * model, suffixed with '_id'.
  428. * - `unique`: If true (default value) cake will first delete existing relationship
  429. * records in the foreign keys table before inserting new ones, when updating a
  430. * record. So existing associations need to be passed again when updating.
  431. * To prevent deletion of existing relationship records, set this key to a string 'keepExisting'.
  432. * - `conditions`: An SQL fragment used to filter related model records. It's good
  433. * practice to use model names in SQL fragments: "Comment.status = 1" is always
  434. * better than just "status = 1."
  435. * - `fields`: A list of fields to be retrieved when the associated model data is
  436. * fetched. Returns all fields by default.
  437. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
  438. * - `limit`: The maximum number of associated rows you want returned.
  439. * - `offset`: The number of associated rows to skip over (given the current
  440. * conditions and order) before fetching and associating.
  441. * - `finderQuery`, A complete SQL query CakePHP
  442. * can use to fetch associated model records. This should
  443. * be used in situations that require very custom results.
  444. *
  445. * @var array
  446. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm
  447. */
  448. public $hasAndBelongsToMany = array();
  449. /**
  450. * List of behaviors to load when the model object is initialized. Settings can be
  451. * passed to behaviors by using the behavior name as index. Eg:
  452. *
  453. * public $actsAs = array('Translate', 'MyBehavior' => array('setting1' => 'value1'))
  454. *
  455. * @var array
  456. * @link http://book.cakephp.org/2.0/en/models/behaviors.html#using-behaviors
  457. */
  458. public $actsAs = null;
  459. /**
  460. * Holds the Behavior objects currently bound to this model.
  461. *
  462. * @var BehaviorCollection
  463. */
  464. public $Behaviors = null;
  465. /**
  466. * Whitelist of fields allowed to be saved.
  467. *
  468. * @var array
  469. */
  470. public $whitelist = array();
  471. /**
  472. * Whether or not to cache sources for this model.
  473. *
  474. * @var bool
  475. */
  476. public $cacheSources = true;
  477. /**
  478. * Type of find query currently executing.
  479. *
  480. * @var string
  481. */
  482. public $findQueryType = null;
  483. /**
  484. * Number of associations to recurse through during find calls. Fetches only
  485. * the first level by default.
  486. *
  487. * @var int
  488. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive
  489. */
  490. public $recursive = 1;
  491. /**
  492. * The column name(s) and direction(s) to order find results by default.
  493. *
  494. * public $order = "Post.created DESC";
  495. * public $order = array("Post.view_count DESC", "Post.rating DESC");
  496. *
  497. * @var string
  498. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#order
  499. */
  500. public $order = null;
  501. /**
  502. * Array of virtual fields this model has. Virtual fields are aliased
  503. * SQL expressions. Fields added to this property will be read as other fields in a model
  504. * but will not be saveable.
  505. *
  506. * `public $virtualFields = array('two' => '1 + 1');`
  507. *
  508. * Is a simplistic example of how to set virtualFields
  509. *
  510. * @var array
  511. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#virtualfields
  512. */
  513. public $virtualFields = array();
  514. /**
  515. * Default list of association keys.
  516. *
  517. * @var array
  518. */
  519. protected $_associationKeys = array(
  520. 'belongsTo' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'counterCache'),
  521. 'hasOne' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'dependent'),
  522. 'hasMany' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'dependent', 'exclusive', 'finderQuery', 'counterQuery'),
  523. 'hasAndBelongsToMany' => array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery')
  524. );
  525. /**
  526. * Holds provided/generated association key names and other data for all associations.
  527. *
  528. * @var array
  529. */
  530. protected $_associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  531. // @codingStandardsIgnoreStart
  532. /**
  533. * Holds model associations temporarily to allow for dynamic (un)binding.
  534. *
  535. * @var array
  536. */
  537. public $__backAssociation = array();
  538. /**
  539. * Back inner association
  540. *
  541. * @var array
  542. */
  543. public $__backInnerAssociation = array();
  544. /**
  545. * Back original association
  546. *
  547. * @var array
  548. */
  549. public $__backOriginalAssociation = array();
  550. /**
  551. * Back containable association
  552. *
  553. * @var array
  554. */
  555. public $__backContainableAssociation = array();
  556. /**
  557. * Safe update mode
  558. * If true, this prevents Model::save() from generating a query with WHERE 1 = 1 on race condition.
  559. *
  560. * @var bool
  561. */
  562. public $__safeUpdateMode = false;
  563. // @codingStandardsIgnoreEnd
  564. /**
  565. * If true, afterFind will be passed consistent formatted $results in case of $primary is false.
  566. * The format will be such as the following.
  567. *
  568. * ```
  569. * $results = array(
  570. * 0 => array(
  571. * 'ModelName' => array(
  572. * 'field1' => 'value1',
  573. * 'field2' => 'value2'
  574. * )
  575. * )
  576. * );
  577. * ```
  578. *
  579. * @var bool
  580. */
  581. public $useConsistentAfterFind = true;
  582. /**
  583. * The ID of the model record that was last inserted.
  584. *
  585. * @var int
  586. */
  587. protected $_insertID = null;
  588. /**
  589. * Has the datasource been configured.
  590. *
  591. * @var bool
  592. * @see Model::getDataSource
  593. */
  594. protected $_sourceConfigured = false;
  595. /**
  596. * List of valid finder method options, supplied as the first parameter to find().
  597. *
  598. * @var array
  599. */
  600. public $findMethods = array(
  601. 'all' => true, 'first' => true, 'count' => true,
  602. 'neighbors' => true, 'list' => true, 'threaded' => true
  603. );
  604. /**
  605. * Instance of the CakeEventManager this model is using
  606. * to dispatch inner events.
  607. *
  608. * @var CakeEventManager
  609. */
  610. protected $_eventManager = null;
  611. /**
  612. * Instance of the ModelValidator
  613. *
  614. * @var ModelValidator
  615. */
  616. protected $_validator = null;
  617. /**
  618. * Constructor. Binds the model's database table to the object.
  619. *
  620. * If `$id` is an array it can be used to pass several options into the model.
  621. *
  622. * - `id`: The id to start the model on.
  623. * - `table`: The table to use for this model.
  624. * - `ds`: The connection name this model is connected to.
  625. * - `name`: The name of the model eg. Post.
  626. * - `alias`: The alias of the model, this is used for registering the instance in the `ClassRegistry`.
  627. * eg. `ParentThread`
  628. *
  629. * ### Overriding Model's __construct method.
  630. *
  631. * When overriding Model::__construct() be careful to include and pass in all 3 of the
  632. * arguments to `parent::__construct($id, $table, $ds);`
  633. *
  634. * ### Dynamically creating models
  635. *
  636. * You can dynamically create model instances using the $id array syntax.
  637. *
  638. * ```
  639. * $Post = new Model(array('table' => 'posts', 'name' => 'Post', 'ds' => 'connection2'));
  640. * ```
  641. *
  642. * Would create a model attached to the posts table on connection2. Dynamic model creation is useful
  643. * when you want a model object that contains no associations or attached behaviors.
  644. *
  645. * @param bool|int|string|array $id Set this ID for this model on startup,
  646. * can also be an array of options, see above.
  647. * @param string $table Name of database table to use.
  648. * @param string $ds DataSource connection name.
  649. */
  650. public function __construct($id = false, $table = null, $ds = null) {
  651. parent::__construct();
  652. if (is_array($id)) {
  653. extract(array_merge(
  654. array(
  655. 'id' => $this->id, 'table' => $this->useTable, 'ds' => $this->useDbConfig,
  656. 'name' => $this->name, 'alias' => $this->alias, 'plugin' => $this->plugin
  657. ),
  658. $id
  659. ));
  660. }
  661. if ($this->plugin === null) {
  662. $this->plugin = (isset($plugin) ? $plugin : $this->plugin);
  663. }
  664. if ($this->name === null) {
  665. $this->name = (isset($name) ? $name : get_class($this));
  666. }
  667. if ($this->alias === null) {
  668. $this->alias = (isset($alias) ? $alias : $this->name);
  669. }
  670. if ($this->primaryKey === null) {
  671. $this->primaryKey = 'id';
  672. }
  673. ClassRegistry::addObject($this->alias, $this);
  674. $this->id = $id;
  675. unset($id);
  676. if ($table === false) {
  677. $this->useTable = false;
  678. } elseif ($table) {
  679. $this->useTable = $table;
  680. }
  681. if ($ds !== null) {
  682. $this->useDbConfig = $ds;
  683. }
  684. if (is_subclass_of($this, 'AppModel')) {
  685. $merge = array('actsAs', 'findMethods');
  686. $parentClass = get_parent_class($this);
  687. if ($parentClass !== 'AppModel') {
  688. $this->_mergeVars($merge, $parentClass);
  689. }
  690. $this->_mergeVars($merge, 'AppModel');
  691. }
  692. $this->_mergeVars(array('findMethods'), 'Model');
  693. $this->Behaviors = new BehaviorCollection();
  694. if ($this->useTable !== false) {
  695. if ($this->useTable === null) {
  696. $this->useTable = Inflector::tableize($this->name);
  697. }
  698. if (!$this->displayField) {
  699. unset($this->displayField);
  700. }
  701. $this->table = $this->useTable;
  702. $this->tableToModel[$this->table] = $this->alias;
  703. } elseif ($this->table === false) {
  704. $this->table = Inflector::tableize($this->name);
  705. }
  706. if ($this->tablePrefix === null) {
  707. unset($this->tablePrefix);
  708. }
  709. $this->_createLinks();
  710. $this->Behaviors->init($this->alias, $this->actsAs);
  711. }
  712. /**
  713. * Returns a list of all events that will fire in the model during it's lifecycle.
  714. * You can override this function to add your own listener callbacks
  715. *
  716. * @return array
  717. */
  718. public function implementedEvents() {
  719. return array(
  720. 'Model.beforeFind' => array('callable' => 'beforeFind', 'passParams' => true),
  721. 'Model.afterFind' => array('callable' => 'afterFind', 'passParams' => true),
  722. 'Model.beforeValidate' => array('callable' => 'beforeValidate', 'passParams' => true),
  723. 'Model.afterValidate' => array('callable' => 'afterValidate'),
  724. 'Model.beforeSave' => array('callable' => 'beforeSave', 'passParams' => true),
  725. 'Model.afterSave' => array('callable' => 'afterSave', 'passParams' => true),
  726. 'Model.beforeDelete' => array('callable' => 'beforeDelete', 'passParams' => true),
  727. 'Model.afterDelete' => array('callable' => 'afterDelete'),
  728. );
  729. }
  730. /**
  731. * Returns the CakeEventManager manager instance that is handling any callbacks.
  732. * You can use this instance to register any new listeners or callbacks to the
  733. * model events, or create your own events and trigger them at will.
  734. *
  735. * @return CakeEventManager
  736. */
  737. public function getEventManager() {
  738. if (empty($this->_eventManager)) {
  739. $this->_eventManager = new CakeEventManager();
  740. $this->_eventManager->attach($this->Behaviors);
  741. $this->_eventManager->attach($this);
  742. }
  743. return $this->_eventManager;
  744. }
  745. /**
  746. * Handles custom method calls, like findBy<field> for DB models,
  747. * and custom RPC calls for remote data sources.
  748. *
  749. * @param string $method Name of method to call.
  750. * @param array $params Parameters for the method.
  751. * @return mixed Whatever is returned by called method
  752. */
  753. public function __call($method, $params) {
  754. $result = $this->Behaviors->dispatchMethod($this, $method, $params);
  755. if ($result !== array('unhandled')) {
  756. return $result;
  757. }
  758. return $this->getDataSource()->query($method, $params, $this);
  759. }
  760. /**
  761. * Handles the lazy loading of model associations by looking in the association arrays for the requested variable
  762. *
  763. * @param string $name variable tested for existence in class
  764. * @return bool true if the variable exists (if is a not loaded model association it will be created), false otherwise
  765. */
  766. public function __isset($name) {
  767. $className = false;
  768. foreach ($this->_associations as $type) {
  769. if (isset($name, $this->{$type}[$name])) {
  770. $className = empty($this->{$type}[$name]['className']) ? $name : $this->{$type}[$name]['className'];
  771. break;
  772. } elseif (isset($name, $this->__backAssociation[$type][$name])) {
  773. $className = empty($this->__backAssociation[$type][$name]['className']) ?
  774. $name : $this->__backAssociation[$type][$name]['className'];
  775. break;
  776. } elseif ($type === 'hasAndBelongsToMany') {
  777. foreach ($this->{$type} as $k => $relation) {
  778. if (empty($relation['with'])) {
  779. continue;
  780. }
  781. if (is_array($relation['with'])) {
  782. if (key($relation['with']) === $name) {
  783. $className = $name;
  784. }
  785. } else {
  786. list($plugin, $class) = pluginSplit($relation['with']);
  787. if ($class === $name) {
  788. $className = $relation['with'];
  789. }
  790. }
  791. if ($className) {
  792. $assocKey = $k;
  793. $dynamic = !empty($relation['dynamicWith']);
  794. break(2);
  795. }
  796. }
  797. }
  798. }
  799. if (!$className) {
  800. return false;
  801. }
  802. list($plugin, $className) = pluginSplit($className);
  803. if (!ClassRegistry::isKeySet($className) && !empty($dynamic)) {
  804. $this->{$className} = new AppModel(array(
  805. 'name' => $className,
  806. 'table' => $this->hasAndBelongsToMany[$assocKey]['joinTable'],
  807. 'ds' => $this->useDbConfig
  808. ));
  809. } else {
  810. $this->_constructLinkedModel($name, $className, $plugin);
  811. }
  812. if (!empty($assocKey)) {
  813. $this->hasAndBelongsToMany[$assocKey]['joinTable'] = $this->{$name}->table;
  814. if (count($this->{$name}->schema()) <= 2 && $this->{$name}->primaryKey !== false) {
  815. $this->{$name}->primaryKey = $this->hasAndBelongsToMany[$assocKey]['foreignKey'];
  816. }
  817. }
  818. return true;
  819. }
  820. /**
  821. * Returns the value of the requested variable if it can be set by __isset()
  822. *
  823. * @param string $name variable requested for it's value or reference
  824. * @return mixed value of requested variable if it is set
  825. */
  826. public function __get($name) {
  827. if ($name === 'displayField') {
  828. return $this->displayField = $this->hasField(array('title', 'name', $this->primaryKey));
  829. }
  830. if ($name === 'tablePrefix') {
  831. $this->setDataSource();
  832. if (property_exists($this, 'tablePrefix') && !empty($this->tablePrefix)) {
  833. return $this->tablePrefix;
  834. }
  835. return $this->tablePrefix = null;
  836. }
  837. if (isset($this->{$name})) {
  838. return $this->{$name};
  839. }
  840. }
  841. /**
  842. * Bind model associations on the fly.
  843. *
  844. * If `$reset` is false, association will not be reset
  845. * to the originals defined in the model
  846. *
  847. * Example: Add a new hasOne binding to the Profile model not
  848. * defined in the model source code:
  849. *
  850. * `$this->User->bindModel(array('hasOne' => array('Profile')));`
  851. *
  852. * Bindings that are not made permanent will be reset by the next Model::find() call on this
  853. * model.
  854. *
  855. * @param array $params Set of bindings (indexed by binding type)
  856. * @param bool $reset Set to false to make the binding permanent
  857. * @return bool Success
  858. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
  859. */
  860. public function bindModel($params, $reset = true) {
  861. foreach ($params as $assoc => $model) {
  862. if ($reset === true && !isset($this->__backAssociation[$assoc])) {
  863. $this->__backAssociation[$assoc] = $this->{$assoc};
  864. }
  865. foreach ($model as $key => $value) {
  866. $assocName = $key;
  867. if (is_numeric($key)) {
  868. $assocName = $value;
  869. $value = array();
  870. }
  871. $this->{$assoc}[$assocName] = $value;
  872. if (property_exists($this, $assocName)) {
  873. unset($this->{$assocName});
  874. }
  875. if ($reset === false && isset($this->__backAssociation[$assoc])) {
  876. $this->__backAssociation[$assoc][$assocName] = $value;
  877. }
  878. }
  879. }
  880. $this->_createLinks();
  881. return true;
  882. }
  883. /**
  884. * Turn off associations on the fly.
  885. *
  886. * If $reset is false, association will not be reset
  887. * to the originals defined in the model
  888. *
  889. * Example: Turn off the associated Model Support request,
  890. * to temporarily lighten the User model:
  891. *
  892. * `$this->User->unbindModel(array('hasMany' => array('SupportRequest')));`
  893. * Or alternatively:
  894. * `$this->User->unbindModel(array('hasMany' => 'SupportRequest'));`
  895. *
  896. * Unbound models that are not made permanent will reset with the next call to Model::find()
  897. *
  898. * @param array $params Set of bindings to unbind (indexed by binding type)
  899. * @param bool $reset Set to false to make the unbinding permanent
  900. * @return bool Success
  901. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
  902. */
  903. public function unbindModel($params, $reset = true) {
  904. foreach ($params as $assoc => $models) {
  905. if ($reset === true && !isset($this->__backAssociation[$assoc])) {
  906. $this->__backAssociation[$assoc] = $this->{$assoc};
  907. }
  908. $models = Hash::normalize((array)$models, false);
  909. foreach ($models as $model) {
  910. if ($reset === false && isset($this->__backAssociation[$assoc][$model])) {
  911. unset($this->__backAssociation[$assoc][$model]);
  912. }
  913. unset($this->{$assoc}[$model]);
  914. }
  915. }
  916. return true;
  917. }
  918. /**
  919. * Create a set of associations.
  920. *
  921. * @return void
  922. */
  923. protected function _createLinks() {
  924. foreach ($this->_associations as $type) {
  925. $association =& $this->{$type};
  926. if (!is_array($association)) {
  927. $association = explode(',', $association);
  928. foreach ($association as $i => $className) {
  929. $className = trim($className);
  930. unset ($association[$i]);
  931. $association[$className] = array();
  932. }
  933. }
  934. if (!empty($association)) {
  935. foreach ($association as $assoc => $value) {
  936. $plugin = null;
  937. if (is_numeric($assoc)) {
  938. unset($association[$assoc]);
  939. $assoc = $value;
  940. $value = array();
  941. if (strpos($assoc, '.') !== false) {
  942. list($plugin, $assoc) = pluginSplit($assoc, true);
  943. $association[$assoc] = array('className' => $plugin . $assoc);
  944. } else {
  945. $association[$assoc] = $value;
  946. }
  947. }
  948. $this->_generateAssociation($type, $assoc);
  949. }
  950. }
  951. }
  952. }
  953. /**
  954. * Protected helper method to create associated models of a given class.
  955. *
  956. * @param string $assoc Association name
  957. * @param string $className Class name
  958. * @param string $plugin name of the plugin where $className is located
  959. * examples: public $hasMany = array('Assoc' => array('className' => 'ModelName'));
  960. * usage: $this->Assoc->modelMethods();
  961. *
  962. * public $hasMany = array('ModelName');
  963. * usage: $this->ModelName->modelMethods();
  964. * @return void
  965. */
  966. protected function _constructLinkedModel($assoc, $className = null, $plugin = null) {
  967. if (empty($className)) {
  968. $className = $assoc;
  969. }
  970. if (!isset($this->{$assoc}) || $this->{$assoc}->name !== $className) {
  971. if ($plugin) {
  972. $plugin .= '.';
  973. }
  974. $model = array('class' => $plugin . $className, 'alias' => $assoc);
  975. $this->{$assoc} = ClassRegistry::init($model);
  976. if ($plugin) {
  977. ClassRegistry::addObject($plugin . $className, $this->{$assoc});
  978. }
  979. if ($assoc) {
  980. $this->tableToModel[$this->{$assoc}->table] = $assoc;
  981. }
  982. }
  983. }
  984. /**
  985. * Build an array-based association from string.
  986. *
  987. * @param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
  988. * @param string $assocKey Association key.
  989. * @return void
  990. */
  991. protected function _generateAssociation($type, $assocKey) {
  992. $class = $assocKey;
  993. $dynamicWith = false;
  994. $assoc =& $this->{$type}[$assocKey];
  995. foreach ($this->_associationKeys[$type] as $key) {
  996. if (!isset($assoc[$key]) || $assoc[$key] === null) {
  997. $data = '';
  998. switch ($key) {
  999. case 'fields':
  1000. $data = '';
  1001. break;
  1002. case 'foreignKey':
  1003. $data = (($type === 'belongsTo') ? Inflector::underscore($assocKey) : Inflector::singularize($this->table)) . '_id';
  1004. break;
  1005. case 'associationForeignKey':
  1006. $data = Inflector::singularize($this->{$class}->table) . '_id';
  1007. break;
  1008. case 'with':
  1009. $data = Inflector::camelize(Inflector::singularize($assoc['joinTable']));
  1010. $dynamicWith = true;
  1011. break;
  1012. case 'joinTable':
  1013. $tables = array($this->table, $this->{$class}->table);
  1014. sort($tables);
  1015. $data = $tables[0] . '_' . $tables[1];
  1016. break;
  1017. case 'className':
  1018. $data = $class;
  1019. break;
  1020. case 'unique':
  1021. $data = true;
  1022. break;
  1023. }
  1024. $assoc[$key] = $data;
  1025. }
  1026. if ($dynamicWith) {
  1027. $assoc['dynamicWith'] = true;
  1028. }
  1029. }
  1030. }
  1031. /**
  1032. * Sets a custom table for your model class. Used by your controller to select a database table.
  1033. *
  1034. * @param string $tableName Name of the custom table
  1035. * @throws MissingTableException when database table $tableName is not found on data source
  1036. * @return void
  1037. */
  1038. public function setSource($tableName) {
  1039. $this->setDataSource($this->useDbConfig);
  1040. $db = ConnectionManager::getDataSource($this->useDbConfig);
  1041. if (method_exists($db, 'listSources')) {
  1042. $restore = $db->cacheSources;
  1043. $db->cacheSources = ($restore && $this->cacheSources);
  1044. $sources = $db->listSources();
  1045. $db->cacheSources = $restore;
  1046. if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) {
  1047. throw new MissingTableException(array(
  1048. 'table' => $this->tablePrefix . $tableName,
  1049. 'class' => $this->alias,
  1050. 'ds' => $this->useDbConfig,
  1051. ));
  1052. }
  1053. if ($sources) {
  1054. $this->_schema = null;
  1055. }
  1056. }
  1057. $this->table = $this->useTable = $tableName;
  1058. $this->tableToModel[$this->table] = $this->alias;
  1059. }
  1060. /**
  1061. * This function does two things:
  1062. *
  1063. * 1. it scans the array $one for the primary key,
  1064. * and if that's found, it sets the current id to the value of $one[id].
  1065. * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object.
  1066. * 2. Returns an array with all of $one's keys and values.
  1067. * (Alternative indata: two strings, which are mangled to
  1068. * a one-item, two-dimensional array using $one for a key and $two as its value.)
  1069. *
  1070. * @param string|array|SimpleXmlElement|DomNode $one Array or string of data
  1071. * @param string $two Value string for the alternative indata method
  1072. * @return array Data with all of $one's keys and values
  1073. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html
  1074. */
  1075. public function set($one, $two = null) {
  1076. if (!$one) {
  1077. return;
  1078. }
  1079. if (is_object($one)) {
  1080. if ($one instanceof SimpleXMLElement || $one instanceof DOMNode) {
  1081. $one = $this->_normalizeXmlData(Xml::toArray($one));
  1082. } else {
  1083. $one = Set::reverse($one);
  1084. }
  1085. }
  1086. if (is_array($one)) {
  1087. $data = $one;
  1088. if (empty($one[$this->alias])) {
  1089. $data = $this->_setAliasData($one);
  1090. }
  1091. } else {
  1092. $data = array($this->alias => array($one => $two));
  1093. }
  1094. foreach ($data as $modelName => $fieldSet) {
  1095. if (!is_array($fieldSet)) {
  1096. continue;
  1097. }
  1098. if (!isset($this->data[$modelName])) {
  1099. $this->data[$modelName] = array();
  1100. }
  1101. foreach ($fieldSet as $fieldName => $fieldValue) {
  1102. unset($this->validationErrors[$fieldName]);
  1103. if ($modelName === $this->alias && $fieldName === $this->primaryKey) {
  1104. $this->id = $fieldValue;
  1105. }
  1106. if (is_array($fieldValue) || is_object($fieldValue)) {
  1107. $fieldValue = $this->deconstruct($fieldName, $fieldValue);
  1108. }
  1109. $this->data[$modelName][$fieldName] = $fieldValue;
  1110. }
  1111. }
  1112. return $data;
  1113. }
  1114. /**
  1115. * Move values to alias
  1116. *
  1117. * @param array $data Data.
  1118. * @return array
  1119. */
  1120. protected function _setAliasData($data) {
  1121. $models = array_keys($this->getAssociated());
  1122. $schema = array_keys((array)$this->schema());
  1123. foreach ($data as $field => $value) {
  1124. if (in_array($field, $schema) || !in_array($field, $models)) {
  1125. $data[$this->alias][$field] = $value;
  1126. unset($data[$field]);
  1127. }
  1128. }
  1129. return $data;
  1130. }
  1131. /**
  1132. * Normalize `Xml::toArray()` to use in `Model::save()`
  1133. *
  1134. * @param array $xml XML as array
  1135. * @return array
  1136. */
  1137. protected function _normalizeXmlData(array $xml) {
  1138. $return = array();
  1139. foreach ($xml as $key => $value) {
  1140. if (is_array($value)) {
  1141. $return[Inflector::camelize($key)] = $this->_normalizeXmlData($value);
  1142. } elseif ($key[0] === '@') {
  1143. $return[substr($key, 1)] = $value;
  1144. } else {
  1145. $return[$key] = $value;
  1146. }
  1147. }
  1148. return $return;
  1149. }
  1150. /**
  1151. * Deconstructs a complex data type (array or object) into a single field value.
  1152. *
  1153. * @param string $field The name of the field to be deconstructed
  1154. * @param array|object $data An array or object to be deconstructed into a field
  1155. * @return mixed The resulting data that should be assigned to a field
  1156. */
  1157. public function deconstruct($field, $data) {
  1158. if (!is_array($data)) {
  1159. return $data;
  1160. }
  1161. $type = $this->getColumnType($field);
  1162. if (!in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
  1163. return $data;
  1164. }
  1165. $useNewDate = (isset($data['year']) || isset($data['month']) ||
  1166. isset($data['day']) || isset($data['hour']) || isset($data['minute']));
  1167. $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
  1168. $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
  1169. $date = array();
  1170. if (isset($data['meridian']) && empty($data['meridian'])) {
  1171. return null;
  1172. }
  1173. if (isset($data['hour']) &&
  1174. isset($data['meridian']) &&
  1175. !empty($data['hour']) &&
  1176. $data['hour'] != 12 &&
  1177. $data['meridian'] === 'pm'
  1178. ) {
  1179. $data['hour'] = $data['hour'] + 12;
  1180. }
  1181. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && $data['meridian'] === 'am') {
  1182. $data['hour'] = '00';
  1183. }
  1184. if ($type === 'time') {
  1185. foreach ($timeFields as $key => $val) {
  1186. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  1187. $data[$val] = '00';
  1188. } elseif ($data[$val] !== '') {
  1189. $data[$val] = sprintf('%02d', $data[$val]);
  1190. }
  1191. if (!empty($data[$val])) {
  1192. $date[$key] = $data[$val];
  1193. } else {
  1194. return null;
  1195. }
  1196. }
  1197. }
  1198. if ($type === 'datetime' || $type === 'timestamp' || $type === 'date') {
  1199. foreach ($dateFields as $key => $val) {
  1200. if ($val === 'hour' || $val === 'min' || $val === 'sec') {
  1201. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  1202. $data[$val] = '00';
  1203. } else {
  1204. $data[$val] = sprintf('%02d', $data[$val]);
  1205. }
  1206. }
  1207. if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
  1208. return null;
  1209. }
  1210. if (isset($data[$val]) && !empty($data[$val])) {
  1211. $date[$key] = $data[$val];
  1212. }
  1213. }
  1214. }
  1215. if ($useNewDate && !empty($date)) {
  1216. $format = $this->getDataSource()->columns[$type]['format'];
  1217. foreach (array('m', 'd', 'H', 'i', 's') as $index) {
  1218. if (isset($date[$index])) {
  1219. $date[$index] = sprintf('%02d', $date[$index]);
  1220. }
  1221. }
  1222. return str_replace(array_keys($date), array_values($date), $format);
  1223. }
  1224. return $data;
  1225. }
  1226. /**
  1227. * Returns an array of table metadata (column names and types) from the database.
  1228. * $field => keys(type, null, default, key, length, extra)
  1229. *
  1230. * @param bool|string $field Set to true to reload schema, or a string to return a specific field
  1231. * @return array|null Array of table metadata
  1232. */
  1233. public function schema($field = false) {
  1234. if ($this->useTable !== false && (!is_array($this->_schema) || $field === true)) {
  1235. $db = $this->getDataSource();
  1236. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  1237. if (method_exists($db, 'describe')) {
  1238. $this->_schema = $db->describe($this);
  1239. }
  1240. }
  1241. if (!is_string($field)) {
  1242. return $this->_schema;
  1243. }
  1244. if (isset($this->_schema[$field])) {
  1245. return $this->_schema[$field];
  1246. }
  1247. return null;
  1248. }
  1249. /**
  1250. * Returns an associative array of field names and column types.
  1251. *
  1252. * @return array Field types indexed by field name
  1253. */
  1254. public function getColumnTypes() {
  1255. $columns = $this->schema();
  1256. if (empty($columns)) {
  1257. 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);
  1258. }
  1259. $cols = array();
  1260. foreach ($columns as $field => $values) {
  1261. $cols[$field] = $values['type'];
  1262. }
  1263. return $cols;
  1264. }
  1265. /**
  1266. * Returns the column type of a column in the model.
  1267. *
  1268. * @param string $column The name of the model column
  1269. * @return string Column type
  1270. */
  1271. public function getColumnType($column) {
  1272. $cols = $this->schema();
  1273. if (isset($cols[$column]) && isset($cols[$column]['type'])) {
  1274. return $cols[$column]['type'];
  1275. }
  1276. $db = $this->getDataSource();
  1277. $model = null;
  1278. $startQuote = isset($db->startQuote) ? $db->startQuote : null;
  1279. $endQuote = isset($db->endQuote) ? $db->endQuote : null;
  1280. $column = str_replace(array($startQuote, $endQuote), '', $column);
  1281. if (strpos($column, '.')) {
  1282. list($model, $column) = explode('.', $column);
  1283. }
  1284. if (isset($model) && $model != $this->alias && isset($this->{$model})) {
  1285. return $this->{$model}->getColumnType($column);
  1286. }
  1287. if (isset($cols[$column]) && isset($cols[$column]['type'])) {
  1288. return $cols[$column]['type'];
  1289. }
  1290. return null;
  1291. }
  1292. /**
  1293. * Returns true if the supplied field exists in the model's database table.
  1294. *
  1295. * @param string|array $name Name of field to look for, or an array of names
  1296. * @param bool $checkVirtual checks if the field is declared as virtual
  1297. * @return mixed If $name is a string, returns a boolean indicating whether the field exists.
  1298. * If $name is an array of field names, returns the first field that exists,
  1299. * or false if none exist.
  1300. */
  1301. public function hasField($name, $checkVirtual = false) {
  1302. if (is_array($name)) {
  1303. foreach ($name as $n) {
  1304. if ($this->hasField($n, $checkVirtual)) {
  1305. return $n;
  1306. }
  1307. }
  1308. return false;
  1309. }
  1310. if ($checkVirtual && !empty($this->virtualFields) && $this->isVirtualField($name)) {
  1311. return true;
  1312. }
  1313. if (empty($this->_schema)) {
  1314. $this->schema();
  1315. }
  1316. if ($this->_schema) {
  1317. return isset($this->_schema[$name]);
  1318. }
  1319. return false;
  1320. }
  1321. /**
  1322. * Check that a method is callable on a model. This will check both the model's own methods, its
  1323. * inherited methods and methods that could be callable through behaviors.
  1324. *
  1325. * @param string $method The method to be called.
  1326. * @return bool True on method being callable.
  1327. */
  1328. public function hasMethod($method) {
  1329. if (method_exists($this, $method)) {
  1330. return true;
  1331. }
  1332. return $this->Behaviors->hasMethod($method);
  1333. }
  1334. /**
  1335. * Returns true if the supplied field is a model Virtual Field
  1336. *
  1337. * @param string $field Name of field to look for
  1338. * @return bool indicating whether the field exists as a model virtual field.
  1339. */
  1340. public function isVirtualField($field) {
  1341. if (empty($this->virtualFields) || !is_string($field)) {
  1342. return false;
  1343. }
  1344. if (isset($this->virtualFields[$field])) {
  1345. return true;
  1346. }
  1347. if (strpos($field, '.') !== false) {
  1348. list($model, $field) = explode('.', $field);
  1349. if ($model === $this->alias && isset($this->virtualFields[$field])) {
  1350. return true;
  1351. }
  1352. }
  1353. return false;
  1354. }
  1355. /**
  1356. * Returns the expression for a model virtual field
  1357. *
  1358. * @param string $field Name of field to look for
  1359. * @return mixed If $field is string expression bound to virtual field $field
  1360. * If $field is null, returns an array of all model virtual fields
  1361. * or false if none $field exist.
  1362. */
  1363. public function getVirtualField($field = null) {
  1364. if (!$field) {
  1365. return empty($this->virtualFields) ? false : $this->virtualFields;
  1366. }
  1367. if ($this->isVirtualField($field)) {
  1368. if (strpos($field, '.') !== false) {
  1369. list(, $field) = pluginSplit($field);
  1370. }
  1371. return $this->virtualFields[$field];
  1372. }
  1373. return false;
  1374. }
  1375. /**
  1376. * Initializes the model for writing a new record, loading the default values
  1377. * for those fields that are not defined in $data, and clearing previous validation errors.
  1378. * Especially helpful for saving data in loops.
  1379. *
  1380. * @param bool|array $data Optional data array to assign to the model after it is created. If null or false,
  1381. * schema data defaults are not merged.
  1382. * @param bool $filterKey If true, overwrites any primary key input with an empty value
  1383. * @return array The current Model::data; after merging $data and/or defaults from database
  1384. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-create-array-data-array
  1385. */
  1386. public function create($data = array(), $filterKey = false) {
  1387. $defaults = array();
  1388. $this->id = false;
  1389. $this->data = array();
  1390. $this->validationErrors = array();
  1391. if ($data !== null && $data !== false) {
  1392. $schema = (array)$this->schema();
  1393. foreach ($schema as $field => $properties) {
  1394. if ($this->primaryKey !== $field && isset($properties['default']) && $properties['default'] !== '') {
  1395. $defaults[$field] = $properties['default'];
  1396. }
  1397. }
  1398. $this->set($defaults);
  1399. $this->set($data);
  1400. }
  1401. if ($filterKey) {
  1402. $this->set($this->primaryKey, false);
  1403. }
  1404. return $this->data;
  1405. }
  1406. /**
  1407. * This function is a convenient wrapper class to create(false) and, as the name suggests, clears the id, data, and validation errors.
  1408. *
  1409. * @return bool Always true upon success
  1410. * @see Model::create()
  1411. */
  1412. public function clear() {
  1413. $this->create(false);
  1414. return true;
  1415. }
  1416. /**
  1417. * Returns a list of fields from the database, and sets the current model
  1418. * data (Model::$data) with the record found.
  1419. *
  1420. * @param string|array $fields String of single field name, or an array of field names.
  1421. * @param int|string $id The ID of the record to read
  1422. * @return array Array of database fields, or false if not found
  1423. * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-read
  1424. */
  1425. public function read($fields = null, $id = null) {
  1426. $this->validationErrors = array();
  1427. if ($id) {
  1428. $this->id = $id;
  1429. }
  1430. $id = $this->id;
  1431. if (is_array($this->id)) {
  1432. $id = $this->id[0];
  1433. }
  1434. if ($id !== null && $id !== false) {
  1435. $this->data = $this->find('first', array(
  1436. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
  1437. 'fields' => $fields
  1438. ));
  1439. return $this->data;
  1440. }
  1441. return false;
  1442. }
  1443. /**
  1444. * Returns the contents of a single field given the supplied conditions, in the
  1445. * supplied order.
  1446. *
  1447. * @param string $name Name of field to get
  1448. * @param array $conditions SQL conditions (defaults to NULL)
  1449. * @param string $order SQL ORDER BY fragment
  1450. * @return string field contents, or false if not found
  1451. * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-field
  1452. */
  1453. public function field($name, $conditions = null, $order = null) {
  1454. if ($conditions === null && $this->id !== false) {
  1455. $conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
  1456. }
  1457. $recursive = $this->recursive;
  1458. if ($this->recursive >= 1) {
  1459. $recursive = -1;
  1460. }
  1461. $fields = $name;
  1462. $data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'));
  1463. if (!$data) {
  1464. return false;
  1465. }
  1466. if (strpos($name, '.') === false) {
  1467. if (isset($data[$this->alias][$name])) {
  1468. return $data[$this->alias][$name];
  1469. }
  1470. } else {
  1471. $name = explode('.', $name);
  1472. if (isset($data[$name[0]][$name[1]])) {
  1473. return $data[$name[0]][$name[1]];
  1474. }
  1475. }
  1476. if (isset($data[0]) && count($data[0]) > 0) {
  1477. return array_shift($data[0]);
  1478. }
  1479. }
  1480. /**
  1481. * Saves the value of a single field to the database, based on the current
  1482. * model ID.
  1483. *
  1484. * @param string $name Name of the table field
  1485. * @param mixed $value Value of the field
  1486. * @param bool|array $validate Either a boolean, or an array.
  1487. * If a boolean, indicates whether or not to validate before saving.
  1488. * If an array, allows co…

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