PageRenderTime 72ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Cake/Model/Model.php

https://github.com/vgarcias/expediamedicus
PHP | 3408 lines | 1819 code | 277 blank | 1312 comment | 518 complexity | c4f0a555d98d9220a62ff3dc40308c84 MD5 | raw file
  1. <?php
  2. /**
  3. * Object-relational mapper.
  4. *
  5. * DBO-backed object data model, for mapping database tables to Cake objects.
  6. *
  7. * PHP versions 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package Cake.Model
  18. * @since CakePHP(tm) v 0.10.0.0
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. App::uses('ClassRegistry', 'Utility');
  22. App::uses('Validation', 'Utility');
  23. App::uses('String', 'Utility');
  24. App::uses('Hash', 'Utility');
  25. App::uses('BehaviorCollection', 'Model');
  26. App::uses('ModelBehavior', 'Model');
  27. App::uses('ModelValidator', 'Model');
  28. App::uses('ConnectionManager', 'Model');
  29. App::uses('Xml', 'Utility');
  30. App::uses('CakeEvent', 'Event');
  31. App::uses('CakeEventListener', 'Event');
  32. App::uses('CakeEventManager', 'Event');
  33. /**
  34. * Object-relational mapper.
  35. *
  36. * DBO-backed object data model.
  37. * Automatically selects a database table name based on a pluralized lowercase object class name
  38. * (i.e. class 'User' => table 'users'; class 'Man' => table 'men')
  39. * The table is required to have at least 'id auto_increment' primary key.
  40. *
  41. * @package Cake.Model
  42. * @link http://book.cakephp.org/2.0/en/models.html
  43. */
  44. class Model extends Object implements CakeEventListener {
  45. /**
  46. * The name of the DataSource connection that this Model uses
  47. *
  48. * The value must be an attribute name that you defined in `app/Config/database.php`
  49. * or created using `ConnectionManager::create()`.
  50. *
  51. * @var string
  52. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#usedbconfig
  53. */
  54. public $useDbConfig = 'default';
  55. /**
  56. * Custom database table name, or null/false if no table association is desired.
  57. *
  58. * @var string
  59. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#usetable
  60. */
  61. public $useTable = null;
  62. /**
  63. * Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements.
  64. *
  65. * This field is also used in `find('list')` when called with no extra parameters in the fields list
  66. *
  67. * @var string
  68. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#displayfield
  69. */
  70. public $displayField = null;
  71. /**
  72. * Value of the primary key ID of the record that this model is currently pointing to.
  73. * Automatically set after database insertions.
  74. *
  75. * @var mixed
  76. */
  77. public $id = false;
  78. /**
  79. * Container for the data that this model gets from persistent storage (usually, a database).
  80. *
  81. * @var array
  82. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#data
  83. */
  84. public $data = array();
  85. /**
  86. * Holds physical schema/database name for this model. Automatically set during Model creation.
  87. *
  88. * @var string
  89. * @access public
  90. */
  91. public $schemaName = null;
  92. /**
  93. * Table name for this Model.
  94. *
  95. * @var string
  96. */
  97. public $table = false;
  98. /**
  99. * The name of the primary key field for this model.
  100. *
  101. * @var string
  102. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#primaryKey
  103. */
  104. public $primaryKey = null;
  105. /**
  106. * Field-by-field table metadata.
  107. *
  108. * @var array
  109. */
  110. protected $_schema = null;
  111. /**
  112. * List of validation rules. It must be an array with the field name as key and using
  113. * as value one of the following possibilities
  114. *
  115. * ### Validating using regular expressions
  116. *
  117. * {{{
  118. * public $validate = array(
  119. * 'name' => '/^[a-z].+$/i'
  120. * );
  121. * }}}
  122. *
  123. * ### Validating using methods (no parameters)
  124. *
  125. * {{{
  126. * public $validate = array(
  127. * 'name' => 'notEmpty'
  128. * );
  129. * }}}
  130. *
  131. * ### Validating using methods (with parameters)
  132. *
  133. * {{{
  134. * public $validate = array(
  135. * 'age' => array(
  136. * 'rule' => array('between', 5, 25)
  137. * )
  138. * );
  139. * }}}
  140. *
  141. * ### Validating using custom method
  142. *
  143. * {{{
  144. * public $validate = array(
  145. * 'password' => array(
  146. * 'rule' => array('customValidation')
  147. * )
  148. * );
  149. * public function customValidation($data) {
  150. * // $data will contain array('password' => 'value')
  151. * if (isset($this->data[$this->alias]['password2'])) {
  152. * return $this->data[$this->alias]['password2'] === current($data);
  153. * }
  154. * return true;
  155. * }
  156. * }}}
  157. *
  158. * ### Validations with messages
  159. *
  160. * The messages will be used in Model::$validationErrors and can be used in the FormHelper
  161. *
  162. * {{{
  163. * public $validate = array(
  164. * 'age' => array(
  165. * 'rule' => array('between', 5, 25),
  166. * 'message' => array('The age must be between %d and %d.')
  167. * )
  168. * );
  169. * }}}
  170. *
  171. * ### Multiple validations to the same field
  172. *
  173. * {{{
  174. * public $validate = array(
  175. * 'login' => array(
  176. * array(
  177. * 'rule' => 'alphaNumeric',
  178. * 'message' => 'Only alphabets and numbers allowed',
  179. * 'last' => true
  180. * ),
  181. * array(
  182. * 'rule' => array('minLength', 8),
  183. * 'message' => array('Minimum length of %d characters')
  184. * )
  185. * )
  186. * );
  187. * }}}
  188. *
  189. * ### Valid keys in validations
  190. *
  191. * - `rule`: String with method name, regular expression (started by slash) or array with method and parameters
  192. * - `message`: String with the message or array if have multiple parameters. See http://php.net/sprintf
  193. * - `last`: Boolean value to indicate if continue validating the others rules if the current fail [Default: true]
  194. * - `required`: Boolean value to indicate if the field must be present on save
  195. * - `allowEmpty`: Boolean value to indicate if the field can be empty
  196. * - `on`: Possible values: `update`, `create`. Indicate to apply this rule only on update or create
  197. *
  198. * @var array
  199. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#validate
  200. * @link http://book.cakephp.org/2.0/en/models/data-validation.html
  201. */
  202. public $validate = array();
  203. /**
  204. * List of validation errors.
  205. *
  206. * @var array
  207. */
  208. public $validationErrors = array();
  209. /**
  210. * Name of the validation string domain to use when translating validation errors.
  211. *
  212. * @var string
  213. */
  214. public $validationDomain = null;
  215. /**
  216. * Database table prefix for tables in model.
  217. *
  218. * @var string
  219. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#tableprefix
  220. */
  221. public $tablePrefix = null;
  222. /**
  223. * Name of the model.
  224. *
  225. * @var string
  226. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#name
  227. */
  228. public $name = null;
  229. /**
  230. * Alias name for model.
  231. *
  232. * @var string
  233. */
  234. public $alias = null;
  235. /**
  236. * List of table names included in the model description. Used for associations.
  237. *
  238. * @var array
  239. */
  240. public $tableToModel = array();
  241. /**
  242. * Whether or not to cache queries for this model. This enables in-memory
  243. * caching only, the results are not stored beyond the current request.
  244. *
  245. * @var boolean
  246. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#cachequeries
  247. */
  248. public $cacheQueries = false;
  249. /**
  250. * Detailed list of belongsTo associations.
  251. *
  252. * ### Basic usage
  253. *
  254. * `public $belongsTo = array('Group', 'Department');`
  255. *
  256. * ### Detailed configuration
  257. *
  258. * {{{
  259. * public $belongsTo = array(
  260. * 'Group',
  261. * 'Department' => array(
  262. * 'className' => 'Department',
  263. * 'foreignKey' => 'department_id'
  264. * )
  265. * );
  266. * }}}
  267. *
  268. * ### Possible keys in association
  269. *
  270. * - `className`: the classname of the model being associated to the current model.
  271. * If you're defining a 'Profile belongsTo User' relationship, the className key should equal 'User.'
  272. * - `foreignKey`: the name of the foreign key found in the current model. This is
  273. * especially handy if you need to define multiple belongsTo relationships. The default
  274. * value for this key is the underscored, singular name of the other model, suffixed with '_id'.
  275. * - `conditions`: An SQL fragment used to filter related model records. It's good
  276. * practice to use model names in SQL fragments: 'User.active = 1' is always
  277. * better than just 'active = 1.'
  278. * - `type`: the type of the join to use in the SQL query, default is LEFT which
  279. * may not fit your needs in all situations, INNER may be helpful when you want
  280. * everything from your main and associated models or nothing at all!(effective
  281. * when used with some conditions of course). (NB: type value is in lower case - i.e. left, inner)
  282. * - `fields`: A list of fields to be retrieved when the associated model data is
  283. * fetched. Returns all fields by default.
  284. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
  285. * - `counterCache`: If set to true the associated Model will automatically increase or
  286. * decrease the "[singular_model_name]_count" field in the foreign table whenever you do
  287. * a save() or delete(). If its a string then its the field name to use. The value in the
  288. * counter field represents the number of related rows.
  289. * - `counterScope`: Optional conditions array to use for updating counter cache field.
  290. *
  291. * @var array
  292. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#belongsto
  293. */
  294. public $belongsTo = array();
  295. /**
  296. * Detailed list of hasOne associations.
  297. *
  298. * ### Basic usage
  299. *
  300. * `public $hasOne = array('Profile', 'Address');`
  301. *
  302. * ### Detailed configuration
  303. *
  304. * {{{
  305. * public $hasOne = array(
  306. * 'Profile',
  307. * 'Address' => array(
  308. * 'className' => 'Address',
  309. * 'foreignKey' => 'user_id'
  310. * )
  311. * );
  312. * }}}
  313. *
  314. * ### Possible keys in association
  315. *
  316. * - `className`: the classname of the model being associated to the current model.
  317. * If you're defining a 'User hasOne Profile' relationship, the className key should equal 'Profile.'
  318. * - `foreignKey`: the name of the foreign key found in the other model. This is
  319. * especially handy if you need to define multiple hasOne relationships.
  320. * The default value for this key is the underscored, singular name of the
  321. * current model, suffixed with '_id'. In the example above it would default to 'user_id'.
  322. * - `conditions`: An SQL fragment used to filter related model records. It's good
  323. * practice to use model names in SQL fragments: "Profile.approved = 1" is
  324. * always better than just "approved = 1."
  325. * - `fields`: A list of fields to be retrieved when the associated model data is
  326. * fetched. Returns all fields by default.
  327. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
  328. * - `dependent`: When the dependent key is set to true, and the model's delete()
  329. * method is called with the cascade parameter set to true, associated model
  330. * records are also deleted. In this case we set it true so that deleting a
  331. * User will also delete her associated Profile.
  332. *
  333. * @var array
  334. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasone
  335. */
  336. public $hasOne = array();
  337. /**
  338. * Detailed list of hasMany associations.
  339. *
  340. * ### Basic usage
  341. *
  342. * `public $hasMany = array('Comment', 'Task');`
  343. *
  344. * ### Detailed configuration
  345. *
  346. * {{{
  347. * public $hasMany = array(
  348. * 'Comment',
  349. * 'Task' => array(
  350. * 'className' => 'Task',
  351. * 'foreignKey' => 'user_id'
  352. * )
  353. * );
  354. * }}}
  355. *
  356. * ### Possible keys in association
  357. *
  358. * - `className`: the classname of the model being associated to the current model.
  359. * If you're defining a 'User hasMany Comment' relationship, the className key should equal 'Comment.'
  360. * - `foreignKey`: the name of the foreign key found in the other model. This is
  361. * especially handy if you need to define multiple hasMany relationships. The default
  362. * value for this key is the underscored, singular name of the actual model, suffixed with '_id'.
  363. * - `conditions`: An SQL fragment used to filter related model records. It's good
  364. * practice to use model names in SQL fragments: "Comment.status = 1" is always
  365. * better than just "status = 1."
  366. * - `fields`: A list of fields to be retrieved when the associated model data is
  367. * fetched. Returns all fields by default.
  368. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
  369. * - `limit`: The maximum number of associated rows you want returned.
  370. * - `offset`: The number of associated rows to skip over (given the current
  371. * conditions and order) before fetching and associating.
  372. * - `dependent`: When dependent is set to true, recursive model deletion is
  373. * possible. In this example, Comment records will be deleted when their
  374. * associated User record has been deleted.
  375. * - `exclusive`: When exclusive is set to true, recursive model deletion does
  376. * the delete with a deleteAll() call, instead of deleting each entity separately.
  377. * This greatly improves performance, but may not be ideal for all circumstances.
  378. * - `finderQuery`: A complete SQL query CakePHP can use to fetch associated model
  379. * records. This should be used in situations that require very custom results.
  380. *
  381. * @var array
  382. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany
  383. */
  384. public $hasMany = array();
  385. /**
  386. * Detailed list of hasAndBelongsToMany associations.
  387. *
  388. * ### Basic usage
  389. *
  390. * `public $hasAndBelongsToMany = array('Role', 'Address');`
  391. *
  392. * ### Detailed configuration
  393. *
  394. * {{{
  395. * public $hasAndBelongsToMany = array(
  396. * 'Role',
  397. * 'Address' => array(
  398. * 'className' => 'Address',
  399. * 'foreignKey' => 'user_id',
  400. * 'associationForeignKey' => 'address_id',
  401. * 'joinTable' => 'addresses_users'
  402. * )
  403. * );
  404. * }}}
  405. *
  406. * ### Possible keys in association
  407. *
  408. * - `className`: the classname of the model being associated to the current model.
  409. * If you're defining a 'Recipe HABTM Tag' relationship, the className key should equal 'Tag.'
  410. * - `joinTable`: The name of the join table used in this association (if the
  411. * current table doesn't adhere to the naming convention for HABTM join tables).
  412. * - `with`: Defines the name of the model for the join table. By default CakePHP
  413. * will auto-create a model for you. Using the example above it would be called
  414. * RecipesTag. By using this key you can override this default name. The join
  415. * table model can be used just like any "regular" model to access the join table directly.
  416. * - `foreignKey`: the name of the foreign key found in the current model.
  417. * This is especially handy if you need to define multiple HABTM relationships.
  418. * The default value for this key is the underscored, singular name of the
  419. * current model, suffixed with '_id'.
  420. * - `associationForeignKey`: the name of the foreign key found in the other 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 other
  423. * model, suffixed with '_id'.
  424. * - `unique`: If true (default value) cake will first delete existing relationship
  425. * records in the foreign keys table before inserting new ones, when updating a
  426. * record. So existing associations need to be passed again when updating.
  427. * To prevent deletion of existing relationship records, set this key to a string 'keepExisting'.
  428. * - `conditions`: An SQL fragment used to filter related model records. It's good
  429. * practice to use model names in SQL fragments: "Comment.status = 1" is always
  430. * better than just "status = 1."
  431. * - `fields`: A list of fields to be retrieved when the associated model data is
  432. * fetched. Returns all fields by default.
  433. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
  434. * - `limit`: The maximum number of associated rows you want returned.
  435. * - `offset`: The number of associated rows to skip over (given the current
  436. * conditions and order) before fetching and associating.
  437. * - `finderQuery`, `deleteQuery`, `insertQuery`: A complete SQL query CakePHP
  438. * can use to fetch, delete, or create new associated model records. This should
  439. * be used in situations that require very custom results.
  440. *
  441. * @var array
  442. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm
  443. */
  444. public $hasAndBelongsToMany = array();
  445. /**
  446. * List of behaviors to load when the model object is initialized. Settings can be
  447. * passed to behaviors by using the behavior name as index. Eg:
  448. *
  449. * public $actsAs = array('Translate', 'MyBehavior' => array('setting1' => 'value1'))
  450. *
  451. * @var array
  452. * @link http://book.cakephp.org/2.0/en/models/behaviors.html#using-behaviors
  453. */
  454. public $actsAs = null;
  455. /**
  456. * Holds the Behavior objects currently bound to this model.
  457. *
  458. * @var BehaviorCollection
  459. */
  460. public $Behaviors = null;
  461. /**
  462. * Whitelist of fields allowed to be saved.
  463. *
  464. * @var array
  465. */
  466. public $whitelist = array();
  467. /**
  468. * Whether or not to cache sources for this model.
  469. *
  470. * @var boolean
  471. */
  472. public $cacheSources = true;
  473. /**
  474. * Type of find query currently executing.
  475. *
  476. * @var string
  477. */
  478. public $findQueryType = null;
  479. /**
  480. * Number of associations to recurse through during find calls. Fetches only
  481. * the first level by default.
  482. *
  483. * @var integer
  484. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive
  485. */
  486. public $recursive = 1;
  487. /**
  488. * The column name(s) and direction(s) to order find results by default.
  489. *
  490. * public $order = "Post.created DESC";
  491. * public $order = array("Post.view_count DESC", "Post.rating DESC");
  492. *
  493. * @var string
  494. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#order
  495. */
  496. public $order = null;
  497. /**
  498. * Array of virtual fields this model has. Virtual fields are aliased
  499. * SQL expressions. Fields added to this property will be read as other fields in a model
  500. * but will not be saveable.
  501. *
  502. * `public $virtualFields = array('two' => '1 + 1');`
  503. *
  504. * Is a simplistic example of how to set virtualFields
  505. *
  506. * @var array
  507. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#virtualfields
  508. */
  509. public $virtualFields = array();
  510. /**
  511. * Default list of association keys.
  512. *
  513. * @var array
  514. */
  515. protected $_associationKeys = array(
  516. 'belongsTo' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'counterCache'),
  517. 'hasOne' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'dependent'),
  518. 'hasMany' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'dependent', 'exclusive', 'finderQuery', 'counterQuery'),
  519. 'hasAndBelongsToMany' => array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery')
  520. );
  521. /**
  522. * Holds provided/generated association key names and other data for all associations.
  523. *
  524. * @var array
  525. */
  526. protected $_associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  527. // @codingStandardsIgnoreStart
  528. /**
  529. * Holds model associations temporarily to allow for dynamic (un)binding.
  530. *
  531. * @var array
  532. */
  533. public $__backAssociation = array();
  534. /**
  535. * Back inner association
  536. *
  537. * @var array
  538. */
  539. public $__backInnerAssociation = array();
  540. /**
  541. * Back original association
  542. *
  543. * @var array
  544. */
  545. public $__backOriginalAssociation = array();
  546. /**
  547. * Back containable association
  548. *
  549. * @var array
  550. */
  551. public $__backContainableAssociation = array();
  552. // @codingStandardsIgnoreEnd
  553. /**
  554. * The ID of the model record that was last inserted.
  555. *
  556. * @var integer
  557. */
  558. protected $_insertID = null;
  559. /**
  560. * Has the datasource been configured.
  561. *
  562. * @var boolean
  563. * @see Model::getDataSource
  564. */
  565. protected $_sourceConfigured = false;
  566. /**
  567. * List of valid finder method options, supplied as the first parameter to find().
  568. *
  569. * @var array
  570. */
  571. public $findMethods = array(
  572. 'all' => true, 'first' => true, 'count' => true,
  573. 'neighbors' => true, 'list' => true, 'threaded' => true
  574. );
  575. /**
  576. * Instance of the CakeEventManager this model is using
  577. * to dispatch inner events.
  578. *
  579. * @var CakeEventManager
  580. */
  581. protected $_eventManager = null;
  582. /**
  583. * Instance of the ModelValidator
  584. *
  585. * @var ModelValidator
  586. */
  587. protected $_validator = null;
  588. /**
  589. * Constructor. Binds the model's database table to the object.
  590. *
  591. * If `$id` is an array it can be used to pass several options into the model.
  592. *
  593. * - id - The id to start the model on.
  594. * - table - The table to use for this model.
  595. * - ds - The connection name this model is connected to.
  596. * - name - The name of the model eg. Post.
  597. * - alias - The alias of the model, this is used for registering the instance in the `ClassRegistry`.
  598. * eg. `ParentThread`
  599. *
  600. * ### Overriding Model's __construct method.
  601. *
  602. * When overriding Model::__construct() be careful to include and pass in all 3 of the
  603. * arguments to `parent::__construct($id, $table, $ds);`
  604. *
  605. * ### Dynamically creating models
  606. *
  607. * You can dynamically create model instances using the $id array syntax.
  608. *
  609. * {{{
  610. * $Post = new Model(array('table' => 'posts', 'name' => 'Post', 'ds' => 'connection2'));
  611. * }}}
  612. *
  613. * Would create a model attached to the posts table on connection2. Dynamic model creation is useful
  614. * when you want a model object that contains no associations or attached behaviors.
  615. *
  616. * @param integer|string|array $id Set this ID for this model on startup, can also be an array of options, see above.
  617. * @param string $table Name of database table to use.
  618. * @param string $ds DataSource connection name.
  619. */
  620. public function __construct($id = false, $table = null, $ds = null) {
  621. parent::__construct();
  622. if (is_array($id)) {
  623. extract(array_merge(
  624. array(
  625. 'id' => $this->id, 'table' => $this->useTable, 'ds' => $this->useDbConfig,
  626. 'name' => $this->name, 'alias' => $this->alias
  627. ),
  628. $id
  629. ));
  630. }
  631. if ($this->name === null) {
  632. $this->name = (isset($name) ? $name : get_class($this));
  633. }
  634. if ($this->alias === null) {
  635. $this->alias = (isset($alias) ? $alias : $this->name);
  636. }
  637. if ($this->primaryKey === null) {
  638. $this->primaryKey = 'id';
  639. }
  640. ClassRegistry::addObject($this->alias, $this);
  641. $this->id = $id;
  642. unset($id);
  643. if ($table === false) {
  644. $this->useTable = false;
  645. } elseif ($table) {
  646. $this->useTable = $table;
  647. }
  648. if ($ds !== null) {
  649. $this->useDbConfig = $ds;
  650. }
  651. if (is_subclass_of($this, 'AppModel')) {
  652. $merge = array('actsAs', 'findMethods');
  653. $parentClass = get_parent_class($this);
  654. if ($parentClass !== 'AppModel') {
  655. $this->_mergeVars($merge, $parentClass);
  656. }
  657. $this->_mergeVars($merge, 'AppModel');
  658. }
  659. $this->_mergeVars(array('findMethods'), 'Model');
  660. $this->Behaviors = new BehaviorCollection();
  661. if ($this->useTable !== false) {
  662. if ($this->useTable === null) {
  663. $this->useTable = Inflector::tableize($this->name);
  664. }
  665. if ($this->displayField == null) {
  666. unset($this->displayField);
  667. }
  668. $this->table = $this->useTable;
  669. $this->tableToModel[$this->table] = $this->alias;
  670. } elseif ($this->table === false) {
  671. $this->table = Inflector::tableize($this->name);
  672. }
  673. if ($this->tablePrefix === null) {
  674. unset($this->tablePrefix);
  675. }
  676. $this->_createLinks();
  677. $this->Behaviors->init($this->alias, $this->actsAs);
  678. }
  679. /**
  680. * Returns a list of all events that will fire in the model during it's lifecycle.
  681. * You can override this function to add you own listener callbacks
  682. *
  683. * @return array
  684. */
  685. public function implementedEvents() {
  686. return array(
  687. 'Model.beforeFind' => array('callable' => 'beforeFind', 'passParams' => true),
  688. 'Model.afterFind' => array('callable' => 'afterFind', 'passParams' => true),
  689. 'Model.beforeValidate' => array('callable' => 'beforeValidate', 'passParams' => true),
  690. 'Model.afterValidate' => array('callable' => 'afterValidate'),
  691. 'Model.beforeSave' => array('callable' => 'beforeSave', 'passParams' => true),
  692. 'Model.afterSave' => array('callable' => 'afterSave', 'passParams' => true),
  693. 'Model.beforeDelete' => array('callable' => 'beforeDelete', 'passParams' => true),
  694. 'Model.afterDelete' => array('callable' => 'afterDelete'),
  695. );
  696. }
  697. /**
  698. * Returns the CakeEventManager manager instance that is handling any callbacks.
  699. * You can use this instance to register any new listeners or callbacks to the
  700. * model events, or create your own events and trigger them at will.
  701. *
  702. * @return CakeEventManager
  703. */
  704. public function getEventManager() {
  705. if (empty($this->_eventManager)) {
  706. $this->_eventManager = new CakeEventManager();
  707. $this->_eventManager->attach($this->Behaviors);
  708. $this->_eventManager->attach($this);
  709. }
  710. return $this->_eventManager;
  711. }
  712. /**
  713. * Handles custom method calls, like findBy<field> for DB models,
  714. * and custom RPC calls for remote data sources.
  715. *
  716. * @param string $method Name of method to call.
  717. * @param array $params Parameters for the method.
  718. * @return mixed Whatever is returned by called method
  719. */
  720. public function __call($method, $params) {
  721. $result = $this->Behaviors->dispatchMethod($this, $method, $params);
  722. if ($result !== array('unhandled')) {
  723. return $result;
  724. }
  725. $return = $this->getDataSource()->query($method, $params, $this);
  726. return $return;
  727. }
  728. /**
  729. * Handles the lazy loading of model associations by looking in the association arrays for the requested variable
  730. *
  731. * @param string $name variable tested for existence in class
  732. * @return boolean true if the variable exists (if is a not loaded model association it will be created), false otherwise
  733. */
  734. public function __isset($name) {
  735. $className = false;
  736. foreach ($this->_associations as $type) {
  737. if (isset($name, $this->{$type}[$name])) {
  738. $className = empty($this->{$type}[$name]['className']) ? $name : $this->{$type}[$name]['className'];
  739. break;
  740. } elseif (isset($name, $this->__backAssociation[$type][$name])) {
  741. $className = empty($this->__backAssociation[$type][$name]['className']) ?
  742. $name : $this->__backAssociation[$type][$name]['className'];
  743. break;
  744. } elseif ($type == 'hasAndBelongsToMany') {
  745. foreach ($this->{$type} as $k => $relation) {
  746. if (empty($relation['with'])) {
  747. continue;
  748. }
  749. if (is_array($relation['with'])) {
  750. if (key($relation['with']) === $name) {
  751. $className = $name;
  752. }
  753. } else {
  754. list($plugin, $class) = pluginSplit($relation['with']);
  755. if ($class === $name) {
  756. $className = $relation['with'];
  757. }
  758. }
  759. if ($className) {
  760. $assocKey = $k;
  761. $dynamic = !empty($relation['dynamicWith']);
  762. break(2);
  763. }
  764. }
  765. }
  766. }
  767. if (!$className) {
  768. return false;
  769. }
  770. list($plugin, $className) = pluginSplit($className);
  771. if (!ClassRegistry::isKeySet($className) && !empty($dynamic)) {
  772. $this->{$className} = new AppModel(array(
  773. 'name' => $className,
  774. 'table' => $this->hasAndBelongsToMany[$assocKey]['joinTable'],
  775. 'ds' => $this->useDbConfig
  776. ));
  777. } else {
  778. $this->_constructLinkedModel($name, $className, $plugin);
  779. }
  780. if (!empty($assocKey)) {
  781. $this->hasAndBelongsToMany[$assocKey]['joinTable'] = $this->{$name}->table;
  782. if (count($this->{$name}->schema()) <= 2 && $this->{$name}->primaryKey !== false) {
  783. $this->{$name}->primaryKey = $this->hasAndBelongsToMany[$assocKey]['foreignKey'];
  784. }
  785. }
  786. return true;
  787. }
  788. /**
  789. * Returns the value of the requested variable if it can be set by __isset()
  790. *
  791. * @param string $name variable requested for it's value or reference
  792. * @return mixed value of requested variable if it is set
  793. */
  794. public function __get($name) {
  795. if ($name === 'displayField') {
  796. return $this->displayField = $this->hasField(array('title', 'name', $this->primaryKey));
  797. }
  798. if ($name === 'tablePrefix') {
  799. $this->setDataSource();
  800. if (property_exists($this, 'tablePrefix') && !empty($this->tablePrefix)) {
  801. return $this->tablePrefix;
  802. }
  803. return $this->tablePrefix = null;
  804. }
  805. if (isset($this->{$name})) {
  806. return $this->{$name};
  807. }
  808. }
  809. /**
  810. * Bind model associations on the fly.
  811. *
  812. * If `$reset` is false, association will not be reset
  813. * to the originals defined in the model
  814. *
  815. * Example: Add a new hasOne binding to the Profile model not
  816. * defined in the model source code:
  817. *
  818. * `$this->User->bindModel( array('hasOne' => array('Profile')) );`
  819. *
  820. * Bindings that are not made permanent will be reset by the next Model::find() call on this
  821. * model.
  822. *
  823. * @param array $params Set of bindings (indexed by binding type)
  824. * @param boolean $reset Set to false to make the binding permanent
  825. * @return boolean Success
  826. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
  827. */
  828. public function bindModel($params, $reset = true) {
  829. foreach ($params as $assoc => $model) {
  830. if ($reset === true && !isset($this->__backAssociation[$assoc])) {
  831. $this->__backAssociation[$assoc] = $this->{$assoc};
  832. }
  833. foreach ($model as $key => $value) {
  834. $assocName = $key;
  835. if (is_numeric($key)) {
  836. $assocName = $value;
  837. $value = array();
  838. }
  839. $this->{$assoc}[$assocName] = $value;
  840. if (property_exists($this, $assocName)) {
  841. unset($this->{$assocName});
  842. }
  843. if ($reset === false && isset($this->__backAssociation[$assoc])) {
  844. $this->__backAssociation[$assoc][$assocName] = $value;
  845. }
  846. }
  847. }
  848. $this->_createLinks();
  849. return true;
  850. }
  851. /**
  852. * Turn off associations on the fly.
  853. *
  854. * If $reset is false, association will not be reset
  855. * to the originals defined in the model
  856. *
  857. * Example: Turn off the associated Model Support request,
  858. * to temporarily lighten the User model:
  859. *
  860. * `$this->User->unbindModel( array('hasMany' => array('Supportrequest')) );`
  861. *
  862. * unbound models that are not made permanent will reset with the next call to Model::find()
  863. *
  864. * @param array $params Set of bindings to unbind (indexed by binding type)
  865. * @param boolean $reset Set to false to make the unbinding permanent
  866. * @return boolean Success
  867. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
  868. */
  869. public function unbindModel($params, $reset = true) {
  870. foreach ($params as $assoc => $models) {
  871. if ($reset === true && !isset($this->__backAssociation[$assoc])) {
  872. $this->__backAssociation[$assoc] = $this->{$assoc};
  873. }
  874. foreach ($models as $model) {
  875. if ($reset === false && isset($this->__backAssociation[$assoc][$model])) {
  876. unset($this->__backAssociation[$assoc][$model]);
  877. }
  878. unset($this->{$assoc}[$model]);
  879. }
  880. }
  881. return true;
  882. }
  883. /**
  884. * Create a set of associations.
  885. *
  886. * @return void
  887. */
  888. protected function _createLinks() {
  889. foreach ($this->_associations as $type) {
  890. if (!is_array($this->{$type})) {
  891. $this->{$type} = explode(',', $this->{$type});
  892. foreach ($this->{$type} as $i => $className) {
  893. $className = trim($className);
  894. unset ($this->{$type}[$i]);
  895. $this->{$type}[$className] = array();
  896. }
  897. }
  898. if (!empty($this->{$type})) {
  899. foreach ($this->{$type} as $assoc => $value) {
  900. $plugin = null;
  901. if (is_numeric($assoc)) {
  902. unset ($this->{$type}[$assoc]);
  903. $assoc = $value;
  904. $value = array();
  905. if (strpos($assoc, '.') !== false) {
  906. list($plugin, $assoc) = pluginSplit($assoc, true);
  907. $this->{$type}[$assoc] = array('className' => $plugin . $assoc);
  908. } else {
  909. $this->{$type}[$assoc] = $value;
  910. }
  911. }
  912. $this->_generateAssociation($type, $assoc);
  913. }
  914. }
  915. }
  916. }
  917. /**
  918. * Protected helper method to create associated models of a given class.
  919. *
  920. * @param string $assoc Association name
  921. * @param string $className Class name
  922. * @param string $plugin name of the plugin where $className is located
  923. * examples: public $hasMany = array('Assoc' => array('className' => 'ModelName'));
  924. * usage: $this->Assoc->modelMethods();
  925. *
  926. * public $hasMany = array('ModelName');
  927. * usage: $this->ModelName->modelMethods();
  928. * @return void
  929. */
  930. protected function _constructLinkedModel($assoc, $className = null, $plugin = null) {
  931. if (empty($className)) {
  932. $className = $assoc;
  933. }
  934. if (!isset($this->{$assoc}) || $this->{$assoc}->name !== $className) {
  935. if ($plugin) {
  936. $plugin .= '.';
  937. }
  938. $model = array('class' => $plugin . $className, 'alias' => $assoc);
  939. $this->{$assoc} = ClassRegistry::init($model);
  940. if ($plugin) {
  941. ClassRegistry::addObject($plugin . $className, $this->{$assoc});
  942. }
  943. if ($assoc) {
  944. $this->tableToModel[$this->{$assoc}->table] = $assoc;
  945. }
  946. }
  947. }
  948. /**
  949. * Build an array-based association from string.
  950. *
  951. * @param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
  952. * @param string $assocKey
  953. * @return void
  954. */
  955. protected function _generateAssociation($type, $assocKey) {
  956. $class = $assocKey;
  957. $dynamicWith = false;
  958. foreach ($this->_associationKeys[$type] as $key) {
  959. if (!isset($this->{$type}[$assocKey][$key]) || $this->{$type}[$assocKey][$key] === null) {
  960. $data = '';
  961. switch ($key) {
  962. case 'fields':
  963. $data = '';
  964. break;
  965. case 'foreignKey':
  966. $data = (($type == 'belongsTo') ? Inflector::underscore($assocKey) : Inflector::singularize($this->table)) . '_id';
  967. break;
  968. case 'associationForeignKey':
  969. $data = Inflector::singularize($this->{$class}->table) . '_id';
  970. break;
  971. case 'with':
  972. $data = Inflector::camelize(Inflector::singularize($this->{$type}[$assocKey]['joinTable']));
  973. $dynamicWith = true;
  974. break;
  975. case 'joinTable':
  976. $tables = array($this->table, $this->{$class}->table);
  977. sort ($tables);
  978. $data = $tables[0] . '_' . $tables[1];
  979. break;
  980. case 'className':
  981. $data = $class;
  982. break;
  983. case 'unique':
  984. $data = true;
  985. break;
  986. }
  987. $this->{$type}[$assocKey][$key] = $data;
  988. }
  989. if ($dynamicWith) {
  990. $this->{$type}[$assocKey]['dynamicWith'] = true;
  991. }
  992. }
  993. }
  994. /**
  995. * Sets a custom table for your model class. Used by your controller to select a database table.
  996. *
  997. * @param string $tableName Name of the custom table
  998. * @throws MissingTableException when database table $tableName is not found on data source
  999. * @return void
  1000. */
  1001. public function setSource($tableName) {
  1002. $this->setDataSource($this->useDbConfig);
  1003. $db = ConnectionManager::getDataSource($this->useDbConfig);
  1004. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  1005. if (method_exists($db, 'listSources')) {
  1006. $sources = $db->listSources();
  1007. if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) {
  1008. throw new MissingTableException(array(
  1009. 'table' => $this->tablePrefix . $tableName,
  1010. 'class' => $this->alias,
  1011. 'ds' => $this->useDbConfig,
  1012. ));
  1013. }
  1014. $this->_schema = null;
  1015. }
  1016. $this->table = $this->useTable = $tableName;
  1017. $this->tableToModel[$this->table] = $this->alias;
  1018. }
  1019. /**
  1020. * This function does two things:
  1021. *
  1022. * 1. it scans the array $one for the primary key,
  1023. * and if that's found, it sets the current id to the value of $one[id].
  1024. * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object.
  1025. * 2. Returns an array with all of $one's keys and values.
  1026. * (Alternative indata: two strings, which are mangled to
  1027. * a one-item, two-dimensional array using $one for a key and $two as its value.)
  1028. *
  1029. * @param string|array|SimpleXmlElement|DomNode $one Array or string of data
  1030. * @param string $two Value string for the alternative indata method
  1031. * @return array Data with all of $one's keys and values
  1032. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html
  1033. */
  1034. public function set($one, $two = null) {
  1035. if (!$one) {
  1036. return;
  1037. }
  1038. if (is_object($one)) {
  1039. if ($one instanceof SimpleXMLElement || $one instanceof DOMNode) {
  1040. $one = $this->_normalizeXmlData(Xml::toArray($one));
  1041. } else {
  1042. $one = Set::reverse($one);
  1043. }
  1044. }
  1045. if (is_array($one)) {
  1046. $data = $one;
  1047. if (empty($one[$this->alias])) {
  1048. $data = $this->_setAliasData($one);
  1049. }
  1050. } else {
  1051. $data = array($this->alias => array($one => $two));
  1052. }
  1053. foreach ($data as $modelName => $fieldSet) {
  1054. if (is_array($fieldSet)) {
  1055. foreach ($fieldSet as $fieldName => $fieldValue) {
  1056. if (isset($this->validationErrors[$fieldName])) {
  1057. unset ($this->validationErrors[$fieldName]);
  1058. }
  1059. if ($modelName === $this->alias) {
  1060. if ($fieldName === $this->primaryKey) {
  1061. $this->id = $fieldValue;
  1062. }
  1063. }
  1064. if (is_array($fieldValue) || is_object($fieldValue)) {
  1065. $fieldValue = $this->deconstruct($fieldName, $fieldValue);
  1066. }
  1067. $this->data[$modelName][$fieldName] = $fieldValue;
  1068. }
  1069. }
  1070. }
  1071. return $data;
  1072. }
  1073. /**
  1074. * Move values to alias
  1075. *
  1076. * @param array $data
  1077. * @return array
  1078. */
  1079. protected function _setAliasData($data) {
  1080. $models = array_keys($this->getAssociated());
  1081. $schema = array_keys((array)$this->schema());
  1082. foreach ($data as $field => $value) {
  1083. if (in_array($field, $schema) || !in_array($field, $models)) {
  1084. $data[$this->alias][$field] = $value;
  1085. unset($data[$field]);
  1086. }
  1087. }
  1088. return $data;
  1089. }
  1090. /**
  1091. * Normalize Xml::toArray() to use in Model::save()
  1092. *
  1093. * @param array $xml XML as array
  1094. * @return array
  1095. */
  1096. protected function _normalizeXmlData(array $xml) {
  1097. $return = array();
  1098. foreach ($xml as $key => $value) {
  1099. if (is_array($value)) {
  1100. $return[Inflector::camelize($key)] = $this->_normalizeXmlData($value);
  1101. } elseif ($key[0] === '@') {
  1102. $return[substr($key, 1)] = $value;
  1103. } else {
  1104. $return[$key] = $value;
  1105. }
  1106. }
  1107. return $return;
  1108. }
  1109. /**
  1110. * Deconstructs a complex data type (array or object) into a single field value.
  1111. *
  1112. * @param string $field The name of the field to be deconstructed
  1113. * @param array|object $data An array or object to be deconstructed into a field
  1114. * @return mixed The resulting data that should be assigned to a field
  1115. */
  1116. public function deconstruct($field, $data) {
  1117. if (!is_array($data)) {
  1118. return $data;
  1119. }
  1120. $type = $this->getColumnType($field);
  1121. if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
  1122. $useNewDate = (isset($data['year']) || isset($data['month']) ||
  1123. isset($data['day']) || isset($data['hour']) || isset($data['minute']));
  1124. $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
  1125. $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
  1126. $date = array();
  1127. if (isset($data['meridian']) && empty($data['meridian'])) {
  1128. return null;
  1129. }
  1130. if (
  1131. isset($data['hour']) &&
  1132. isset($data['meridian']) &&
  1133. !empty($data['hour']) &&
  1134. $data['hour'] != 12 &&
  1135. 'pm' == $data['meridian']
  1136. ) {
  1137. $data['hour'] = $data['hour'] + 12;
  1138. }
  1139. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
  1140. $data['hour'] = '00';
  1141. }
  1142. if ($type == 'time') {
  1143. foreach ($timeFields as $key => $val) {
  1144. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  1145. $data[$val] = '00';
  1146. } elseif ($data[$val] !== '') {
  1147. $data[$val] = sprintf('%02d', $data[$val]);
  1148. }
  1149. if (!empty($data[$val])) {
  1150. $date[$key] = $data[$val];
  1151. } else {
  1152. return null;
  1153. }
  1154. }
  1155. }
  1156. if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
  1157. foreach ($dateFields as $key => $val) {
  1158. if ($val == 'hour' || $val == 'min' || $val == 'sec') {
  1159. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  1160. $data[$val] = '00';
  1161. } else {
  1162. $data[$val] = sprintf('%02d', $data[$val]);
  1163. }
  1164. }
  1165. if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
  1166. return null;
  1167. }
  1168. if (isset($data[$val]) && !empty($data[$val])) {
  1169. $date[$key] = $data[$val];
  1170. }
  1171. }
  1172. }
  1173. if ($useNewDate && !empty($date)) {
  1174. $format = $this->getDataSource()->columns[$type]['format'];
  1175. foreach (array('m', 'd', 'H', 'i', 's') as $index) {
  1176. if (isset($date[$index])) {
  1177. $date[$index] = sprintf('%02d', $date[$index]);
  1178. }
  1179. }
  1180. return str_replace(array_keys($date), array_values($date), $format);
  1181. }
  1182. }
  1183. return $data;
  1184. }
  1185. /**
  1186. * Returns an array of table metadata (column names and types) from the database.
  1187. * $field => keys(type, null, default, key, length, extra)
  1188. *
  1189. * @param boolean|string $field Set to true to reload schema, or a string to return a specific field
  1190. * @return array Array of table metadata
  1191. */
  1192. public function schema($field = false) {
  1193. if ($this->useTable !== false && (!is_array($this->_schema) || $field === true)) {
  1194. $db = $this->getDataSource();
  1195. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  1196. if (method_exists($db, 'describe') && $this->useTable !== false) {
  1197. $this->_schema = $db->describe($this);
  1198. } elseif ($this->useTable === false) {
  1199. $this->_schema = array();
  1200. }
  1201. }
  1202. if (is_string($field)) {
  1203. if (isset($this->_schema[$field])) {
  1204. return $this->_schema[$field];
  1205. } else {
  1206. return null;
  1207. }
  1208. }
  1209. return $this->_schema;
  1210. }
  1211. /**
  1212. * Returns an associative array of field names and column types.
  1213. *
  1214. * @return array Field types indexed by field name
  1215. */
  1216. public function getColumnTypes() {
  1217. $columns = $this->schema();
  1218. if (empty($columns)) {
  1219. 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);
  1220. }
  1221. $cols = array();
  1222. foreach ($columns as $field => $values) {
  1223. $cols[$field] = $values['type'];
  1224. }
  1225. return $cols;
  1226. }
  1227. /**
  1228. * Returns the column type of a column in the model.
  1229. *
  1230. * @param string $column The name of the model column
  1231. * @return string Column type
  1232. */
  1233. public function getColumnType($column) {
  1234. $db = $this->getDataSource();
  1235. $cols = $this->schema();
  1236. $model = null;
  1237. $startQuote = isset($db->startQuote) ? $db->startQuote : null;
  1238. $endQuote = isset($db->endQuote) ? $db->endQuote : null;
  1239. $column = str_replace(array($startQuote, $endQuote), '', $column);
  1240. if (strpos($column, '.')) {
  1241. list($model, $column) = explode('.', $column);
  1242. }
  1243. if ($model != $this->alias && isset($this->{$model})) {
  1244. return $this->{$model}->getColumnType($column);
  1245. }
  1246. if (isset($cols[$column]) && isset($cols[$column]['type'])) {
  1247. return $cols[$column]['type'];
  1248. }
  1249. return null;
  1250. }
  1251. /**
  1252. * Returns true if the supplied field exists in the model's database table.
  1253. *
  1254. * @param string|array $name Name of field to look for, or an array of names
  1255. * @param boolean $checkVirtual checks if the field is declared as virtual
  1256. * @return mixed If $name is a string, returns a boolean indicating whether the field exists.
  1257. * If $name is an array of field names, returns the first field that exists,
  1258. * or false if none exist.
  1259. */
  1260. public function hasField($name, $checkVirtual = false) {
  1261. if (is_array($name)) {
  1262. foreach ($name as $n) {
  1263. if ($this->hasField($n, $checkVirtual)) {
  1264. return $n;
  1265. }
  1266. }
  1267. return false;
  1268. }
  1269. if ($checkVirtual && !empty($this->virtualFields)) {
  1270. if ($this->isVirtualField($name)) {
  1271. return true;
  1272. }
  1273. }
  1274. if (empty($this->_schema)) {
  1275. $this->schema();
  1276. }
  1277. if ($this->_schema != null) {
  1278. return isset($this->_schema[$name]);
  1279. }
  1280. return false;
  1281. }
  1282. /**
  1283. * Check that a method is callable on a model. This will check both the model's own methods, its
  1284. * inherited methods and methods that could be callable through behaviors.
  1285. *
  1286. * @param string $method The method to be called.
  1287. * @return boolean True on method being callable.
  1288. */
  1289. public function hasMethod($method) {
  1290. if (method_exists($this, $method)) {
  1291. return true;
  1292. }
  1293. if ($this->Behaviors->hasMethod($method)) {
  1294. return true;
  1295. }
  1296. return false;
  1297. }
  1298. /**
  1299. * Returns true if the supplied field is a model Virtual Field
  1300. *
  1301. * @param string $field Name of field to look for
  1302. * @return boolean indicating whether the field exists as a model virtual field.
  1303. */
  1304. public function isVirtualField($field) {
  1305. if (empty($this->virtualFields) || !is_string($field)) {
  1306. return false;
  1307. }
  1308. if (isset($this->virtualFields[$field])) {
  1309. return true;
  1310. }
  1311. if (strpos($field, '.') !== false) {
  1312. list($model, $field) = explode('.', $field);
  1313. if ($model == $this->alias && isset($this->virtualFields[$field])) {
  1314. return true;
  1315. }
  1316. }
  1317. return false;
  1318. }
  1319. /**
  1320. * Returns the expression for a model virtual field
  1321. *
  1322. * @param string $field Name of field to look for
  1323. * @return mixed If $field is string expression bound to virtual field $field
  1324. * If $field is null, returns an array of all model virtual fields
  1325. * or false if none $field exist.
  1326. */
  1327. public function getVirtualField($field = null) {
  1328. if ($field == null) {
  1329. return empty($this->virtualFields) ? false : $this->virtualFields;
  1330. }
  1331. if ($this->isVirtualField($field)) {
  1332. if (strpos($field, '.') !== false) {
  1333. list($model, $field) = explode('.', $field);
  1334. }
  1335. return $this->virtualFields[$field];
  1336. }
  1337. return false;
  1338. }
  1339. /**
  1340. * Initializes the model for writing a new record, loading the default values
  1341. * for those fields that are not defined in $data, and clearing previous validation errors.
  1342. * Especially helpful for saving data in loops.
  1343. *
  1344. * @param boolean|array $data Optional data array to assign to the model after it is created. If null or false,
  1345. * schema data defaults are not merged.
  1346. * @param boolean $filterKey If true, overwrites any primary key input with an empty value
  1347. * @return array The current Model::data; after merging $data and/or defaults from database
  1348. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-create-array-data-array
  1349. */
  1350. public function create($data = array(), $filterKey = false) {
  1351. $defaults = array();
  1352. $this->id = false;
  1353. $this->data = array();
  1354. $this->validationErrors = array();
  1355. if ($data !== null && $data !== false) {
  1356. foreach ($this->schema() as $field => $properties) {
  1357. if ($this->primaryKey !== $field && isset($properties['default']) && $properties['default'] !== '') {
  1358. $defaults[$field] = $properties['default'];
  1359. }
  1360. }
  1361. $this->set($defaults);
  1362. $this->set($data);
  1363. }
  1364. if ($filterKey) {
  1365. $this->set($this->primaryKey, false);
  1366. }
  1367. return $this->data;
  1368. }
  1369. /**
  1370. * Returns a list of fields from the database, and sets the current model
  1371. * data (Model::$data) with the record found.
  1372. *
  1373. * @param string|array $fields String of single field name, or an array of field names.
  1374. * @param integer|string $id The ID of the record to read
  1375. * @return array Array of database fields, or false if not found
  1376. * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-read
  1377. */
  1378. public function read($fields = null, $id = null) {
  1379. $this->validationErrors = array();
  1380. if ($id != null) {
  1381. $this->id = $id;
  1382. }
  1383. $id = $this->id;
  1384. if (is_array($this->id)) {
  1385. $id = $this->id[0];
  1386. }
  1387. if ($id !== null && $id !== false) {
  1388. $this->data = $this->find('first', array(
  1389. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
  1390. 'fields' => $fields
  1391. ));
  1392. return $this->data;
  1393. } else {
  1394. return false;
  1395. }
  1396. }
  1397. /**
  1398. * Returns the contents of a single field given the supplied conditions, in the
  1399. * supplied order.
  1400. *
  1401. * @param string $name Name of field to get
  1402. * @param array $conditions SQL conditions (defaults to NULL)
  1403. * @param string $order SQL ORDER BY fragment
  1404. * @return string field contents, or false if not found
  1405. * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-field
  1406. */
  1407. public function field($name, $conditions = null, $order = null) {
  1408. if ($conditions === null && $this->id !== false) {
  1409. $conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
  1410. }
  1411. if ($this->recursive >= 1) {
  1412. $recursive = -1;
  1413. } else {
  1414. $recursive = $this->recursive;
  1415. }
  1416. $fields = $name;
  1417. if ($data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'))) {
  1418. if (strpos($name, '.') === false) {
  1419. if (isset($data[$this->alias][$name])) {
  1420. return $data[$this->alias][$name];
  1421. }
  1422. } else {
  1423. $name = explode('.', $name);
  1424. if (isset($data[$name[0]][$name[1]])) {
  1425. return $data[$name[0]][$name[1]];
  1426. }
  1427. }
  1428. if (isset($data[0]) && count($data[0]) > 0) {
  1429. return array_shift($data[0]);
  1430. }
  1431. } else {
  1432. return false;
  1433. }
  1434. }
  1435. /**
  1436. * Saves the value of a single field to the database, based on the current
  1437. * model ID.
  1438. *
  1439. * @param string $name Name of the table field
  1440. * @param mixed $value Value of the field
  1441. * @param array $validate See $options param in Model::save(). Does not respect 'fieldList' key if passed
  1442. * @return boolean See Model::save()
  1443. * @see Model::save()
  1444. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savefield-string-fieldname-string-fieldvalue-validate-false
  1445. */
  1446. public function saveField($name, $value, $validate = false) {
  1447. $id = $this->id;
  1448. $this->create(false);
  1449. if (is_array($validate)) {
  1450. $options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate);
  1451. } else {
  1452. $options = array('validate' => $validate, 'fieldList' => array($name));
  1453. }
  1454. return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options);
  1455. }
  1456. /**
  1457. * Saves model data (based on white-list, if supplied) to the database. By
  1458. * default, validation occurs before save.
  1459. *
  1460. * @param array $data Data to save.
  1461. * @param boolean|array $validate Either a boolean, or an array.
  1462. * If a boolean, indicates whether or not to validate before saving.
  1463. * If an array, allows control of validate, callbacks, and fieldList
  1464. * @param array $fieldList List of fields to allow to be written
  1465. * @return mixed On success Model::$data if its not empty or true, false on failure
  1466. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html
  1467. */
  1468. public function save($data = null, $validate = true, $fieldList = array()) {
  1469. $defaults = array('validate' => true, 'fieldList' => array(), 'callbacks' => true);
  1470. $_whitelist = $this->whitelist;
  1471. $fields = array();
  1472. if (!is_array($validate)) {
  1473. $options = array_merge($defaults, compact('validate', 'fieldList', 'callbacks'));
  1474. } else {
  1475. $options = array_merge($defaults, $validate);
  1476. }
  1477. if (!empty($options['fieldList'])) {
  1478. if (!empty($options['fieldList'][$this->alias]) && is_array($options['fieldList'][$this->alias])) {
  1479. $this->whitelist = $options['fieldList'][$this->alias];
  1480. } else {
  1481. $this->whitelist = $options['fieldList'];
  1482. }
  1483. } elseif ($options['fieldList'] === null) {
  1484. $this->whitelist = array();
  1485. }
  1486. $this->set($data);
  1487. if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) {
  1488. return false;
  1489. }
  1490. foreach (array('created', 'updated', 'modified') as $field) {
  1491. $keyPresentAndEmpty = (
  1492. isset($this->data[$this->alias]) &&
  1493. array_key_exists($field, $this->data[$this->alias]) &&
  1494. $this->data[$this->alias][$field] === null
  1495. );
  1496. if ($keyPresentAndEmpty) {
  1497. unset($this->data[$this->alias][$field]);
  1498. }
  1499. }
  1500. $exists = $this->exists();
  1501. $dateFields = array('modified', 'updated');
  1502. if (!$exists) {
  1503. $dateFields[] = 'created';
  1504. }
  1505. if (isset($this->data[$this->alias])) {
  1506. $fields = array_keys($this->data[$this->alias]);
  1507. }
  1508. if ($options['validate'] && !$this->validates($options)) {
  1509. $this->whitelist = $_whitelist;
  1510. return false;
  1511. }
  1512. $db = $this->getDataSource();
  1513. foreach ($dateFields as $updateCol) {
  1514. if ($this->hasField($updateCol) && !in_array($updateCol, $fields)) {
  1515. $default = array('formatter' => 'date');
  1516. $colType = array_merge($default, $db->columns[$this->getColumnType($updateCol)]);
  1517. if (!array_key_exists('format', $colType)) {
  1518. $time = strtotime('now');
  1519. } else {
  1520. $time = call_user_func($colType['formatter'], $colType['format']);
  1521. }
  1522. if (!empty($this->whitelist)) {
  1523. $this->whitelist[] = $updateCol;
  1524. }
  1525. $this->set($updateCol, $time);
  1526. }
  1527. }
  1528. if ($options['callbacks'] === true || $options['callbacks'] === 'before') {
  1529. $event = new CakeEvent('Model.beforeSave', $this, array($options));
  1530. list($event->break, $event->breakOn) = array(true, array(false, null));
  1531. $this->getEventManager()->dispatch($event);
  1532. if (!$event->result) {
  1533. $this->whitelist = $_whitelist;
  1534. return false;
  1535. }
  1536. }
  1537. if (empty($this->data[$this->alias][$this->primaryKey])) {
  1538. unset($this->data[$this->alias][$this->primaryKey]);
  1539. }
  1540. $fields = $values = array();
  1541. foreach ($this->data as $n => $v) {
  1542. if (isset($this->hasAndBelongsToMany[$n])) {
  1543. if (isset($v[$n])) {
  1544. $v = $v[$n];
  1545. }
  1546. $joined[$n] = $v;
  1547. } else {
  1548. if ($n === $this->alias) {
  1549. foreach (array('created', 'updated', 'modified') as $field) {
  1550. if (array_key_exists($field, $v) && empty($v[$field])) {
  1551. unset($v[$field]);
  1552. }
  1553. }
  1554. foreach ($v as $x => $y) {
  1555. if ($this->hasField($x) && (empty($this->whitelist) || in_array($x, $this->whitelist))) {
  1556. list($fields[], $values[]) = array($x, $y);
  1557. }
  1558. }
  1559. }
  1560. }
  1561. }
  1562. $count = count($fields);
  1563. if (!$exists && $count > 0) {
  1564. $this->id = false;
  1565. }
  1566. $success = true;
  1567. $created = false;
  1568. if ($count > 0) {
  1569. $cache = $this->_prepareUpdateFields(array_combine($fields, $values));
  1570. if (!empty($this->id)) {
  1571. $success = (bool)$db->update($this, $fields, $values);
  1572. } else {
  1573. $fInfo = $this->schema($this->primaryKey);
  1574. $isUUID = ($fInfo['length'] == 36 &&
  1575. ($fInfo['type'] === 'string' || $fInfo['type'] === 'binary')
  1576. );
  1577. if (empty($this->data[$this->alias][$this->primaryKey]) && $isUUID) {
  1578. if (array_key_exists($this->primaryKey, $this->data[$this->alias])) {
  1579. $j = array_search($this->primaryKey, $fields);
  1580. $values[$j] = String::uuid();
  1581. } else {
  1582. list($fields[], $values[]) = array($this->primaryKey, String::uuid());
  1583. }
  1584. }
  1585. if (!$db->create($this, $fields, $values)) {
  1586. $success = $created = false;
  1587. } else {
  1588. $created = true;
  1589. }
  1590. }
  1591. if ($success && !empty($this->belongsTo)) {
  1592. $this->updateCounterCache($cache, $created);
  1593. }
  1594. }
  1595. if (!empty($joined) && $success === true) {
  1596. $this->_saveMulti($joined, $this->id, $db);
  1597. }
  1598. if ($success && $count > 0) {
  1599. if (!empty($this->data)) {
  1600. if ($created) {
  1601. $this->data[$this->alias][$this->primaryKey] = $this->id;
  1602. }
  1603. }
  1604. if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
  1605. $event = new CakeEvent('Model.afterSave', $this, array($created, $options));
  1606. $this->getEventManager()->dispatch($event);
  1607. }
  1608. if (!empty($this->data)) {
  1609. $success = $this->data;
  1610. }
  1611. $this->data = false;
  1612. $this->_clearCache();
  1613. $this->validationErrors = array();
  1614. }
  1615. $this->whitelist = $_whitelist;
  1616. return $success;
  1617. }
  1618. /**
  1619. * Saves model hasAndBelongsToMany data to the database.
  1620. *
  1621. * @param array $joined Data to save
  1622. * @param integer|string $id ID of record in this model
  1623. * @param DataSource $db
  1624. * @return void
  1625. */
  1626. protected function _saveMulti($joined, $id, $db) {
  1627. foreach ($joined as $assoc => $data) {
  1628. if (isset($this->hasAndBelongsToMany[$assoc])) {
  1629. list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
  1630. $keyInfo = $this->{$join}->schema($this->{$join}->primaryKey);
  1631. if ($with = $this->hasAndBelongsToMany[$assoc]['with']) {
  1632. $withModel = is_array($with) ? key($with) : $with;
  1633. list($pluginName, $withModel) = pluginSplit($withModel);
  1634. $dbMulti = $this->{$withModel}->getDataSource();
  1635. } else {
  1636. $dbMulti = $db;
  1637. }
  1638. $isUUID = !empty($this->{$join}->primaryKey) && (
  1639. $keyInfo['length'] == 36 && (
  1640. $keyInfo['type'] === 'string' ||
  1641. $keyInfo['type'] === 'binary'
  1642. )
  1643. );
  1644. $newData = $newValues = $newJoins = array();
  1645. $primaryAdded = false;
  1646. $fields = array(
  1647. $dbMulti->name($this->hasAndBelongsToMany[$assoc]['foreignKey']),
  1648. $dbMulti->name($this->hasAndBelongsToMany[$assoc]['associationForeignKey'])
  1649. );
  1650. $idField = $db->name($this->{$join}->primaryKey);
  1651. if ($isUUID && !in_array($idField, $fields)) {
  1652. $fields[] = $idField;
  1653. $primaryAdded = true;
  1654. }
  1655. foreach ((array)$data as $row) {
  1656. if ((is_string($row) && (strlen($row) == 36 || strlen($row) == 16)) || is_numeric($row)) {
  1657. $newJoins[] = $row;
  1658. $values = array($id, $row);
  1659. if ($isUUID && $primaryAdded) {
  1660. $values[] = String::uuid();
  1661. }
  1662. $newValues[$row] = $values;
  1663. unset($values);
  1664. } elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1665. if (!empty($row[$this->{$join}->primaryKey])) {
  1666. $newJoins[] = $row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']];
  1667. }
  1668. $newData[] = $row;
  1669. } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1670. if (!empty($row[$join][$this->{$join}->primaryKey])) {
  1671. $newJoins[] = $row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']];
  1672. }
  1673. $newData[] = $row[$join];
  1674. }
  1675. }
  1676. $keepExisting = $this->hasAndBelongsToMany[$assoc]['unique'] === 'keepExisting';
  1677. if ($this->hasAndBelongsToMany[$assoc]['unique']) {
  1678. $conditions = array(
  1679. $join . '.' . $this->hasAndBelongsToMany[$assoc]['foreignKey'] => $id
  1680. );
  1681. if (!empty($this->hasAndBelongsToMany[$assoc]['conditions'])) {
  1682. $conditions = array_merge($conditions, (array)$this->hasAndBelongsToMany[$assoc]['conditions']);
  1683. }
  1684. $associationForeignKey = $this->{$join}->alias . '.' . $this->hasAndBelongsToMany[$assoc]['associationForeignKey'];
  1685. $links = $this->{$join}->find('all', array(
  1686. 'conditions' => $conditions,
  1687. 'recursive' => empty($this->hasAndBelongsToMany[$assoc]['conditions']) ? -1 : 0,
  1688. 'fields' => $associationForeignKey,
  1689. ));
  1690. $oldLinks = Hash::extract($links, "{n}.{$associationForeignKey}");
  1691. if (!empty($oldLinks)) {
  1692. if ($keepExisting && !empty($newJoins)) {
  1693. $conditions[$associationForeignKey] = array_diff($oldLinks, $newJoins);
  1694. } else {
  1695. $conditions[$associationForeignKey] = $oldLinks;
  1696. }
  1697. $dbMulti->delete($this->{$join}, $conditions);
  1698. }
  1699. }
  1700. if (!empty($newData)) {
  1701. foreach ($newData as $data) {
  1702. $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $id;
  1703. if (empty($data[$this->{$join}->primaryKey])) {
  1704. $this->{$join}->create();
  1705. }
  1706. $this->{$join}->save($data);
  1707. }
  1708. }
  1709. if (!empty($newValues)) {
  1710. if ($keepExisting && !empty($links)) {
  1711. foreach ($links as $link) {
  1712. $oldJoin = $link[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']];
  1713. if (! in_array($oldJoin, $newJoins) ) {
  1714. $conditions[$associationForeignKey] = $oldJoin;
  1715. $db->delete($this->{$join}, $conditions);
  1716. } else {
  1717. unset($newValues[$oldJoin]);
  1718. }
  1719. }
  1720. $newValues = array_values($newValues);
  1721. }
  1722. if (!empty($newValues)) {
  1723. $dbMulti->insertMulti($this->{$join}, $fields, $newValues);
  1724. }
  1725. }
  1726. }
  1727. }
  1728. }
  1729. /**
  1730. * Updates the counter cache of belongsTo associations after a save or delete operation
  1731. *
  1732. * @param array $keys Optional foreign key data, defaults to the information $this->data
  1733. * @param boolean $created True if a new record was created, otherwise only associations with
  1734. * 'counterScope' defined get updated
  1735. * @return void
  1736. */
  1737. public function updateCounterCache($keys = array(), $created = false) {
  1738. $keys = empty($keys) ? $this->data[$this->alias] : $keys;
  1739. $keys['old'] = isset($keys['old']) ? $keys['old'] : array();
  1740. foreach ($this->belongsTo as $parent => $assoc) {
  1741. if (!empty($assoc['counterCache'])) {
  1742. if (!is_array($assoc['counterCache'])) {
  1743. if (isset($assoc['counterScope'])) {
  1744. $assoc['counterCache'] = array($assoc['counterCache'] => $assoc['counterScope']);
  1745. } else {
  1746. $assoc['counterCache'] = array($assoc['counterCache'] => array());
  1747. }
  1748. }
  1749. $foreignKey = $assoc['foreignKey'];
  1750. $fkQuoted = $this->escapeField($assoc['foreignKey']);
  1751. foreach ($assoc['counterCache'] as $field => $conditions) {
  1752. if (!is_string($field)) {
  1753. $field = Inflector::underscore($this->alias) . '_count';
  1754. }
  1755. if (!$this->{$parent}->hasField($field)) {
  1756. continue;
  1757. }
  1758. if ($conditions === true) {
  1759. $conditions = array();
  1760. } else {
  1761. $conditions = (array)$conditions;
  1762. }
  1763. if (!array_key_exists($foreignKey, $keys)) {
  1764. $keys[$foreignKey] = $this->field($foreignKey);
  1765. }
  1766. $recursive = (empty($conditions) ? -1 : 0);
  1767. if (isset($keys['old'][$foreignKey])) {
  1768. if ($keys['old'][$foreignKey] != $keys[$foreignKey]) {
  1769. $conditions[$fkQuoted] = $keys['old'][$foreignKey];
  1770. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1771. $this->{$parent}->updateAll(
  1772. array($field => $count),
  1773. array($this->{$parent}->escapeField() => $keys['old'][$foreignKey])
  1774. );
  1775. }
  1776. }
  1777. $conditions[$fkQuoted] = $keys[$foreignKey];
  1778. if ($recursive === 0) {
  1779. $conditions = array_merge($conditions, (array)$conditions);
  1780. }
  1781. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1782. $this->{$parent}->updateAll(
  1783. array($field => $count),
  1784. array($this->{$parent}->escapeField() => $keys[$foreignKey])
  1785. );
  1786. }
  1787. }
  1788. }
  1789. }
  1790. /**
  1791. * Helper method for Model::updateCounterCache(). Checks the fields to be updated for
  1792. *
  1793. * @param array $data The fields of the record that will be updated
  1794. * @return array Returns updated foreign key values, along with an 'old' key containing the old
  1795. * values, or empty if no foreign keys are updated.
  1796. */
  1797. protected function _prepareUpdateFields($data) {
  1798. $foreignKeys = array();
  1799. foreach ($this->belongsTo as $assoc => $info) {
  1800. if ($info['counterCache']) {
  1801. $foreignKeys[$assoc] = $info['foreignKey'];
  1802. }
  1803. }
  1804. $included = array_intersect($foreignKeys, array_keys($data));
  1805. if (empty($included) || empty($this->id)) {
  1806. return array();
  1807. }
  1808. $old = $this->find('first', array(
  1809. 'conditions' => array($this->alias . '.' . $this->primaryKey => $this->id),
  1810. 'fields' => array_values($included),
  1811. 'recursive' => -1
  1812. ));
  1813. return array_merge($data, array('old' => $old[$this->alias]));
  1814. }
  1815. /**
  1816. * Backwards compatible passthrough method for:
  1817. * saveMany(), validateMany(), saveAssociated() and validateAssociated()
  1818. *
  1819. * Saves multiple individual records for a single model; Also works with a single record, as well as
  1820. * all its associated records.
  1821. *
  1822. * #### Options
  1823. *
  1824. * - validate: Set to false to disable validation, true to validate each record before saving,
  1825. * 'first' to validate *all* records before any are saved (default),
  1826. * or 'only' to only validate the records, but not save them.
  1827. * - atomic: If true (default), will attempt to save all records in a single transaction.
  1828. * Should be set to false if database/table does not support transactions.
  1829. * - fieldList: Equivalent to the $fieldList parameter in Model::save().
  1830. * It should be an associate array with model name as key and array of fields as value. Eg.
  1831. * {{{
  1832. * array(
  1833. * 'SomeModel' => array('field'),
  1834. * 'AssociatedModel' => array('field', 'otherfield')
  1835. * )
  1836. * }}}
  1837. * - deep: see saveMany/saveAssociated
  1838. *
  1839. * @param array $data Record data to save. This can be either a numerically-indexed array (for saving multiple
  1840. * records of the same type), or an array indexed by association name.
  1841. * @param array $options Options to use when saving record data, See $options above.
  1842. * @return mixed If atomic: True on success, or false on failure.
  1843. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1844. * depending on whether each record saved successfully.
  1845. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
  1846. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array
  1847. */
  1848. public function saveAll($data = array(), $options = array()) {
  1849. $options = array_merge(array('validate' => 'first'), $options);
  1850. if (Hash::numeric(array_keys($data))) {
  1851. if ($options['validate'] === 'only') {
  1852. return $this->validateMany($data, $options);
  1853. }
  1854. return $this->saveMany($data, $options);
  1855. }
  1856. if ($options['validate'] === 'only') {
  1857. return $this->validateAssociated($data, $options);
  1858. }
  1859. return $this->saveAssociated($data, $options);
  1860. }
  1861. /**
  1862. * Saves multiple individual records for a single model
  1863. *
  1864. * #### Options
  1865. *
  1866. * - validate: Set to false to disable validation, true to validate each record before saving,
  1867. * 'first' to validate *all* records before any are saved (default),
  1868. * - atomic: If true (default), will attempt to save all records in a single transaction.
  1869. * Should be set to false if database/table does not support transactions.
  1870. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1871. * - deep: If set to true, all associated data will be saved as well.
  1872. *
  1873. * @param array $data Record data to save. This should be a numerically-indexed array
  1874. * @param array $options Options to use when saving record data, See $options above.
  1875. * @return mixed If atomic: True on success, or false on failure.
  1876. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1877. * depending on whether each record saved successfully.
  1878. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savemany-array-data-null-array-options-array
  1879. */
  1880. public function saveMany($data = null, $options = array()) {
  1881. if (empty($data)) {
  1882. $data = $this->data;
  1883. }
  1884. $options = array_merge(array('validate' => 'first', 'atomic' => true, 'deep' => false), $options);
  1885. $this->validationErrors = $validationErrors = array();
  1886. if (empty($data) && $options['validate'] !== false) {
  1887. $result = $this->save($data, $options);
  1888. if (!$options['atomic']) {
  1889. return array(!empty($result));
  1890. }
  1891. return !empty($result);
  1892. }
  1893. if ($options['validate'] === 'first') {
  1894. $validates = $this->validateMany($data, $options);
  1895. if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, $validates, true))) {
  1896. return $validates;
  1897. }
  1898. $options['validate'] = false;
  1899. }
  1900. if ($options['atomic']) {
  1901. $db = $this->getDataSource();
  1902. $transactionBegun = $db->begin();
  1903. }
  1904. $return = array();
  1905. foreach ($data as $key => $record) {
  1906. $validates = $this->create(null) !== null;
  1907. $saved = false;
  1908. if ($validates) {
  1909. if ($options['deep']) {
  1910. $saved = $this->saveAssociated($record, array_merge($options, array('atomic' => false)));
  1911. } else {
  1912. $saved = $this->save($record, $options);
  1913. }
  1914. }
  1915. $validates = ($validates && ($saved === true || (is_array($saved) && !in_array(false, $saved, true))));
  1916. if (!$validates) {
  1917. $validationErrors[$key] = $this->validationErrors;
  1918. }
  1919. if (!$options['atomic']) {
  1920. $return[$key] = $validates;
  1921. } elseif (!$validates) {
  1922. break;
  1923. }
  1924. }
  1925. $this->validationErrors = $validationErrors;
  1926. if (!$options['atomic']) {
  1927. return $return;
  1928. }
  1929. if ($validates) {
  1930. if ($transactionBegun) {
  1931. return $db->commit() !== false;
  1932. } else {
  1933. return true;
  1934. }
  1935. }
  1936. $db->rollback();
  1937. return false;
  1938. }
  1939. /**
  1940. * Validates multiple individual records for a single model
  1941. *
  1942. * #### Options
  1943. *
  1944. * - atomic: If true (default), returns boolean. If false returns array.
  1945. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1946. * - deep: If set to true, all associated data will be validated as well.
  1947. *
  1948. * Warning: This method could potentially change the passed argument `$data`,
  1949. * If you do not want this to happen, make a copy of `$data` before passing it
  1950. * to this method
  1951. *
  1952. * @param array $data Record data to validate. This should be a numerically-indexed array
  1953. * @param array $options Options to use when validating record data (see above), See also $options of validates().
  1954. * @return boolean True on success, or false on failure.
  1955. * @return mixed If atomic: True on success, or false on failure.
  1956. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1957. * depending on whether each record validated successfully.
  1958. */
  1959. public function validateMany(&$data, $options = array()) {
  1960. return $this->validator()->validateMany($data, $options);
  1961. }
  1962. /**
  1963. * Saves a single record, as well as all its directly associated records.
  1964. *
  1965. * #### Options
  1966. *
  1967. * - `validate` Set to `false` to disable validation, `true` to validate each record before saving,
  1968. * 'first' to validate *all* records before any are saved(default),
  1969. * - `atomic` If true (default), will attempt to save all records in a single transaction.
  1970. * Should be set to false if database/table does not support transactions.
  1971. * - fieldList: Equivalent to the $fieldList parameter in Model::save().
  1972. * It should be an associate array with model name as key and array of fields as value. Eg.
  1973. * {{{
  1974. * array(
  1975. * 'SomeModel' => array('field'),
  1976. * 'AssociatedModel' => array('field', 'otherfield')
  1977. * )
  1978. * }}}
  1979. * - deep: If set to true, not only directly associated data is saved, but deeper nested associated data as well.
  1980. *
  1981. * @param array $data Record data to save. This should be an array indexed by association name.
  1982. * @param array $options Options to use when saving record data, See $options above.
  1983. * @return mixed If atomic: True on success, or false on failure.
  1984. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1985. * depending on whether each record saved successfully.
  1986. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
  1987. */
  1988. public function saveAssociated($data = null, $options = array()) {
  1989. if (empty($data)) {
  1990. $data = $this->data;
  1991. }
  1992. $options = array_merge(array('validate' => 'first', 'atomic' => true, 'deep' => false), $options);
  1993. $this->validationErrors = $validationErrors = array();
  1994. if (empty($data) && $options['validate'] !== false) {
  1995. $result = $this->save($data, $options);
  1996. if (!$options['atomic']) {
  1997. return array(!empty($result));
  1998. }
  1999. return !empty($result);
  2000. }
  2001. if ($options['validate'] === 'first') {
  2002. $validates = $this->validateAssociated($data, $options);
  2003. if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, Hash::flatten($validates), true))) {
  2004. return $validates;
  2005. }
  2006. $options['validate'] = false;
  2007. }
  2008. if ($options['atomic']) {
  2009. $db = $this->getDataSource();
  2010. $transactionBegun = $db->begin();
  2011. }
  2012. $associations = $this->getAssociated();
  2013. $return = array();
  2014. $validates = true;
  2015. foreach ($data as $association => $values) {
  2016. $notEmpty = !empty($values[$association]) || (!isset($values[$association]) && !empty($values));
  2017. if (isset($associations[$association]) && $associations[$association] === 'belongsTo' && $notEmpty) {
  2018. $validates = $this->{$association}->create(null) !== null;
  2019. $saved = false;
  2020. if ($validates) {
  2021. if ($options['deep']) {
  2022. $saved = $this->{$association}->saveAssociated($values, array_merge($options, array('atomic' => false)));
  2023. } else {
  2024. $saved = $this->{$association}->save($values, array_merge($options, array('atomic' => false)));
  2025. }
  2026. $validates = ($saved === true || (is_array($saved) && !in_array(false, $saved, true)));
  2027. }
  2028. if ($validates) {
  2029. $key = $this->belongsTo[$association]['foreignKey'];
  2030. if (isset($data[$this->alias])) {
  2031. $data[$this->alias][$key] = $this->{$association}->id;
  2032. } else {
  2033. $data = array_merge(array($key => $this->{$association}->id), $data, array($key => $this->{$association}->id));
  2034. }
  2035. } else {
  2036. $validationErrors[$association] = $this->{$association}->validationErrors;
  2037. }
  2038. $return[$association] = $validates;
  2039. }
  2040. }
  2041. if ($validates && !($this->create(null) !== null && $this->save($data, $options))) {
  2042. $validationErrors[$this->alias] = $this->validationErrors;
  2043. $validates = false;
  2044. }
  2045. $return[$this->alias] = $validates;
  2046. foreach ($data as $association => $values) {
  2047. if (!$validates) {
  2048. break;
  2049. }
  2050. $notEmpty = !empty($values[$association]) || (!isset($values[$association]) && !empty($values));
  2051. if (isset($associations[$association]) && $notEmpty) {
  2052. $type = $associations[$association];
  2053. $key = $this->{$type}[$association]['foreignKey'];
  2054. switch ($type) {
  2055. case 'hasOne':
  2056. if (isset($values[$association])) {
  2057. $values[$association][$key] = $this->id;
  2058. } else {
  2059. $values = array_merge(array($key => $this->id), $values, array($key => $this->id));
  2060. }
  2061. $validates = $this->{$association}->create(null) !== null;
  2062. $saved = false;
  2063. if ($validates) {
  2064. if ($options['deep']) {
  2065. $saved = $this->{$association}->saveAssociated($values, array_merge($options, array('atomic' => false)));
  2066. } else {
  2067. $saved = $this->{$association}->save($values, $options);
  2068. }
  2069. }
  2070. $validates = ($validates && ($saved === true || (is_array($saved) && !in_array(false, $saved, true))));
  2071. if (!$validates) {
  2072. $validationErrors[$association] = $this->{$association}->validationErrors;
  2073. }
  2074. $return[$association] = $validates;
  2075. break;
  2076. case 'hasMany':
  2077. foreach ($values as $i => $value) {
  2078. if (isset($values[$i][$association])) {
  2079. $values[$i][$association][$key] = $this->id;
  2080. } else {
  2081. $values[$i] = array_merge(array($key => $this->id), $value, array($key => $this->id));
  2082. }
  2083. }
  2084. $_return = $this->{$association}->saveMany($values, array_merge($options, array('atomic' => false)));
  2085. if (in_array(false, $_return, true)) {
  2086. $validationErrors[$association] = $this->{$association}->validationErrors;
  2087. $validates = false;
  2088. }
  2089. $return[$association] = $_return;
  2090. break;
  2091. }
  2092. }
  2093. }
  2094. $this->validationErrors = $validationErrors;
  2095. if (isset($validationErrors[$this->alias])) {
  2096. $this->validationErrors = $validationErrors[$this->alias];
  2097. unset($validationErrors[$this->alias]);
  2098. $this->validationErrors = array_merge($this->validationErrors, $validationErrors);
  2099. }
  2100. if (!$options['atomic']) {
  2101. return $return;
  2102. }
  2103. if ($validates) {
  2104. if ($transactionBegun) {
  2105. return $db->commit() !== false;
  2106. } else {
  2107. return true;
  2108. }
  2109. }
  2110. $db->rollback();
  2111. return false;
  2112. }
  2113. /**
  2114. * Validates a single record, as well as all its directly associated records.
  2115. *
  2116. * #### Options
  2117. *
  2118. * - atomic: If true (default), returns boolean. If false returns array.
  2119. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  2120. * - deep: If set to true, not only directly associated data , but deeper nested associated data is validated as well.
  2121. *
  2122. * Warning: This method could potentially change the passed argument `$data`,
  2123. * If you do not want this to happen, make a copy of `$data` before passing it
  2124. * to this method
  2125. *
  2126. * @param array $data Record data to validate. This should be an array indexed by association name.
  2127. * @param array $options Options to use when validating record data (see above), See also $options of validates().
  2128. * @return array|boolean If atomic: True on success, or false on failure.
  2129. * Otherwise: array similar to the $data array passed, but values are set to true/false
  2130. * depending on whether each record validated successfully.
  2131. */
  2132. public function validateAssociated(&$data, $options = array()) {
  2133. return $this->validator()->validateAssociated($data, $options);
  2134. }
  2135. /**
  2136. * Updates multiple model records based on a set of conditions.
  2137. *
  2138. * @param array $fields Set of fields and values, indexed by fields.
  2139. * Fields are treated as SQL snippets, to insert literal values manually escape your data.
  2140. * @param mixed $conditions Conditions to match, true for all records
  2141. * @return boolean True on success, false on failure
  2142. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-updateall-array-fields-array-conditions
  2143. */
  2144. public function updateAll($fields, $conditions = true) {
  2145. return $this->getDataSource()->update($this, $fields, null, $conditions);
  2146. }
  2147. /**
  2148. * Removes record for given ID. If no ID is given, the current ID is used. Returns true on success.
  2149. *
  2150. * @param integer|string $id ID of record to delete
  2151. * @param boolean $cascade Set to true to delete records that depend on this record
  2152. * @return boolean True on success
  2153. * @link http://book.cakephp.org/2.0/en/models/deleting-data.html
  2154. */
  2155. public function delete($id = null, $cascade = true) {
  2156. if (!empty($id)) {
  2157. $this->id = $id;
  2158. }
  2159. $id = $this->id;
  2160. $event = new CakeEvent('Model.beforeDelete', $this, array($cascade));
  2161. list($event->break, $event->breakOn) = array(true, array(false, null));
  2162. $this->getEventManager()->dispatch($event);
  2163. if (!$event->isStopped()) {
  2164. if (!$this->exists()) {
  2165. return false;
  2166. }
  2167. $db = $this->getDataSource();
  2168. $this->_deleteDependent($id, $cascade);
  2169. $this->_deleteLinks($id);
  2170. $this->id = $id;
  2171. $updateCounterCache = false;
  2172. if (!empty($this->belongsTo)) {
  2173. foreach ($this->belongsTo as $assoc) {
  2174. if (!empty($assoc['counterCache'])) {
  2175. $updateCounterCache = true;
  2176. break;
  2177. }
  2178. }
  2179. if ($updateCounterCache) {
  2180. $keys = $this->find('first', array(
  2181. 'fields' => $this->_collectForeignKeys(),
  2182. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
  2183. 'recursive' => -1,
  2184. 'callbacks' => false
  2185. ));
  2186. }
  2187. }
  2188. if ($db->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) {
  2189. if ($updateCounterCache) {
  2190. $this->updateCounterCache($keys[$this->alias]);
  2191. }
  2192. $this->getEventManager()->dispatch(new CakeEvent('Model.afterDelete', $this));
  2193. $this->_clearCache();
  2194. $this->id = false;
  2195. return true;
  2196. }
  2197. }
  2198. return false;
  2199. }
  2200. /**
  2201. * Cascades model deletes through associated hasMany and hasOne child records.
  2202. *
  2203. * @param string $id ID of record that was deleted
  2204. * @param boolean $cascade Set to true to delete records that depend on this record
  2205. * @return void
  2206. */
  2207. protected function _deleteDependent($id, $cascade) {
  2208. if (!empty($this->__backAssociation)) {
  2209. $savedAssociatons = $this->__backAssociation;
  2210. $this->__backAssociation = array();
  2211. }
  2212. if ($cascade === true) {
  2213. foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) {
  2214. if ($data['dependent'] === true) {
  2215. $model = $this->{$assoc};
  2216. if ($data['foreignKey'] === false && $data['conditions'] && in_array($this->name, $model->getAssociated('belongsTo'))) {
  2217. $model->recursive = 0;
  2218. $conditions = array($this->escapeField(null, $this->name) => $id);
  2219. } else {
  2220. $model->recursive = -1;
  2221. $conditions = array($model->escapeField($data['foreignKey']) => $id);
  2222. if ($data['conditions']) {
  2223. $conditions = array_merge((array)$data['conditions'], $conditions);
  2224. }
  2225. }
  2226. if (isset($data['exclusive']) && $data['exclusive']) {
  2227. $model->deleteAll($conditions);
  2228. } else {
  2229. $records = $model->find('all', array(
  2230. 'conditions' => $conditions, 'fields' => $model->primaryKey
  2231. ));
  2232. if (!empty($records)) {
  2233. foreach ($records as $record) {
  2234. $model->delete($record[$model->alias][$model->primaryKey]);
  2235. }
  2236. }
  2237. }
  2238. }
  2239. }
  2240. }
  2241. if (isset($savedAssociatons)) {
  2242. $this->__backAssociation = $savedAssociatons;
  2243. }
  2244. }
  2245. /**
  2246. * Cascades model deletes through HABTM join keys.
  2247. *
  2248. * @param string $id ID of record that was deleted
  2249. * @return void
  2250. */
  2251. protected function _deleteLinks($id) {
  2252. foreach ($this->hasAndBelongsToMany as $data) {
  2253. list($plugin, $joinModel) = pluginSplit($data['with']);
  2254. $records = $this->{$joinModel}->find('all', array(
  2255. 'conditions' => array($this->{$joinModel}->escapeField($data['foreignKey']) => $id),
  2256. 'fields' => $this->{$joinModel}->primaryKey,
  2257. 'recursive' => -1,
  2258. 'callbacks' => false
  2259. ));
  2260. if (!empty($records)) {
  2261. foreach ($records as $record) {
  2262. $this->{$joinModel}->delete($record[$this->{$joinModel}->alias][$this->{$joinModel}->primaryKey]);
  2263. }
  2264. }
  2265. }
  2266. }
  2267. /**
  2268. * Deletes multiple model records based on a set of conditions.
  2269. *
  2270. * @param mixed $conditions Conditions to match
  2271. * @param boolean $cascade Set to true to delete records that depend on this record
  2272. * @param boolean $callbacks Run callbacks
  2273. * @return boolean True on success, false on failure
  2274. * @link http://book.cakephp.org/2.0/en/models/deleting-data.html#deleteall
  2275. */
  2276. public function deleteAll($conditions, $cascade = true, $callbacks = false) {
  2277. if (empty($conditions)) {
  2278. return false;
  2279. }
  2280. $db = $this->getDataSource();
  2281. if (!$cascade && !$callbacks) {
  2282. return $db->delete($this, $conditions);
  2283. } else {
  2284. $ids = $this->find('all', array_merge(array(
  2285. 'fields' => "{$this->alias}.{$this->primaryKey}",
  2286. 'recursive' => 0), compact('conditions'))
  2287. );
  2288. if ($ids === false) {
  2289. return false;
  2290. }
  2291. $ids = Hash::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}");
  2292. if (empty($ids)) {
  2293. return true;
  2294. }
  2295. if ($callbacks) {
  2296. $_id = $this->id;
  2297. $result = true;
  2298. foreach ($ids as $id) {
  2299. $result = ($result && $this->delete($id, $cascade));
  2300. }
  2301. $this->id = $_id;
  2302. return $result;
  2303. } else {
  2304. foreach ($ids as $id) {
  2305. $this->_deleteLinks($id);
  2306. if ($cascade) {
  2307. $this->_deleteDependent($id, $cascade);
  2308. }
  2309. }
  2310. return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids));
  2311. }
  2312. }
  2313. }
  2314. /**
  2315. * Collects foreign keys from associations.
  2316. *
  2317. * @param string $type
  2318. * @return array
  2319. */
  2320. protected function _collectForeignKeys($type = 'belongsTo') {
  2321. $result = array();
  2322. foreach ($this->{$type} as $assoc => $data) {
  2323. if (isset($data['foreignKey']) && is_string($data['foreignKey'])) {
  2324. $result[$assoc] = $data['foreignKey'];
  2325. }
  2326. }
  2327. return $result;
  2328. }
  2329. /**
  2330. * Returns true if a record with particular ID exists.
  2331. *
  2332. * If $id is not passed it calls Model::getID() to obtain the current record ID,
  2333. * and then performs a Model::find('count') on the currently configured datasource
  2334. * to ascertain the existence of the record in persistent storage.
  2335. *
  2336. * @param integer|string $id ID of record to check for existence
  2337. * @return boolean True if such a record exists
  2338. */
  2339. public function exists($id = null) {
  2340. if ($id === null) {
  2341. $id = $this->getID();
  2342. }
  2343. if ($id === false) {
  2344. return false;
  2345. }
  2346. $conditions = array($this->alias . '.' . $this->primaryKey => $id);
  2347. $query = array('conditions' => $conditions, 'recursive' => -1, 'callbacks' => false);
  2348. return ($this->find('count', $query) > 0);
  2349. }
  2350. /**
  2351. * Returns true if a record that meets given conditions exists.
  2352. *
  2353. * @param array $conditions SQL conditions array
  2354. * @return boolean True if such a record exists
  2355. */
  2356. public function hasAny($conditions = null) {
  2357. return ($this->find('count', array('conditions' => $conditions, 'recursive' => -1)) != false);
  2358. }
  2359. /**
  2360. * Queries the datasource and returns a result set array.
  2361. *
  2362. * Also used to perform notation finds, where the first argument is type of find operation to perform
  2363. * (all / first / count / neighbors / list / threaded),
  2364. * second parameter options for finding ( indexed array, including: 'conditions', 'limit',
  2365. * 'recursive', 'page', 'fields', 'offset', 'order')
  2366. *
  2367. * Eg:
  2368. * {{{
  2369. * find('all', array(
  2370. * 'conditions' => array('name' => 'Thomas Anderson'),
  2371. * 'fields' => array('name', 'email'),
  2372. * 'order' => 'field3 DESC',
  2373. * 'recursive' => 2,
  2374. * 'group' => 'type'
  2375. * ));
  2376. * }}}
  2377. *
  2378. * In addition to the standard query keys above, you can provide Datasource, and behavior specific
  2379. * keys. For example, when using a SQL based datasource you can use the joins key to specify additional
  2380. * joins that should be part of the query.
  2381. *
  2382. * {{{
  2383. * find('all', array(
  2384. * 'conditions' => array('name' => 'Thomas Anderson'),
  2385. * 'joins' => array(
  2386. * array(
  2387. * 'alias' => 'Thought',
  2388. * 'table' => 'thoughts',
  2389. * 'type' => 'LEFT',
  2390. * 'conditions' => '`Thought`.`person_id` = `Person`.`id`'
  2391. * )
  2392. * )
  2393. * ));
  2394. * }}}
  2395. *
  2396. * Behaviors and find types can also define custom finder keys which are passed into find().
  2397. *
  2398. * Specifying 'fields' for notation 'list':
  2399. *
  2400. * - If no fields are specified, then 'id' is used for key and 'model->displayField' is used for value.
  2401. * - If a single field is specified, 'id' is used for key and specified field is used for value.
  2402. * - If three fields are specified, they are used (in order) for key, value and group.
  2403. * - Otherwise, first and second fields are used for key and value.
  2404. *
  2405. * Note: find(list) + database views have issues with MySQL 5.0. Try upgrading to MySQL 5.1 if you
  2406. * have issues with database views.
  2407. *
  2408. * Note: find(count) has its own return values.
  2409. *
  2410. * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
  2411. * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
  2412. * @return array Array of records, or Null on failure.
  2413. * @link http://book.cakephp.org/2.0/en/models/deleting-data.html#deleteall
  2414. */
  2415. public function find($type = 'first', $query = array()) {
  2416. $this->findQueryType = $type;
  2417. $this->id = $this->getID();
  2418. $query = $this->buildQuery($type, $query);
  2419. if (is_null($query)) {
  2420. return null;
  2421. }
  2422. $results = $this->getDataSource()->read($this, $query);
  2423. $this->resetAssociations();
  2424. if ($query['callbacks'] === true || $query['callbacks'] === 'after') {
  2425. $results = $this->_filterResults($results);
  2426. }
  2427. $this->findQueryType = null;
  2428. if ($type === 'all') {
  2429. return $results;
  2430. }
  2431. if ($this->findMethods[$type] === true) {
  2432. return $this->{'_find' . ucfirst($type)}('after', $query, $results);
  2433. }
  2434. }
  2435. /**
  2436. * Builds the query array that is used by the data source to generate the query to fetch the data.
  2437. *
  2438. * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
  2439. * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
  2440. * @return array Query array or null if it could not be build for some reasons
  2441. * @see Model::find()
  2442. */
  2443. public function buildQuery($type = 'first', $query = array()) {
  2444. $query = array_merge(
  2445. array(
  2446. 'conditions' => null, 'fields' => null, 'joins' => array(), 'limit' => null,
  2447. 'offset' => null, 'order' => null, 'page' => 1, 'group' => null, 'callbacks' => true,
  2448. ),
  2449. (array)$query
  2450. );
  2451. if ($type !== 'all') {
  2452. if ($this->findMethods[$type] === true) {
  2453. $query = $this->{'_find' . ucfirst($type)}('before', $query);
  2454. }
  2455. }
  2456. if (!is_numeric($query['page']) || intval($query['page']) < 1) {
  2457. $query['page'] = 1;
  2458. }
  2459. if ($query['page'] > 1 && !empty($query['limit'])) {
  2460. $query['offset'] = ($query['page'] - 1) * $query['limit'];
  2461. }
  2462. if ($query['order'] === null && $this->order !== null) {
  2463. $query['order'] = $this->order;
  2464. }
  2465. $query['order'] = array($query['order']);
  2466. if ($query['callbacks'] === true || $query['callbacks'] === 'before') {
  2467. $event = new CakeEvent('Model.beforeFind', $this, array($query));
  2468. list($event->break, $event->breakOn, $event->modParams) = array(true, array(false, null), 0);
  2469. $this->getEventManager()->dispatch($event);
  2470. if ($event->isStopped()) {
  2471. return null;
  2472. }
  2473. $query = $event->result === true ? $event->data[0] : $event->result;
  2474. }
  2475. return $query;
  2476. }
  2477. /**
  2478. * Handles the before/after filter logic for find('first') operations. Only called by Model::find().
  2479. *
  2480. * @param string $state Either "before" or "after"
  2481. * @param array $query
  2482. * @param array $results
  2483. * @return array
  2484. * @see Model::find()
  2485. */
  2486. protected function _findFirst($state, $query, $results = array()) {
  2487. if ($state === 'before') {
  2488. $query['limit'] = 1;
  2489. return $query;
  2490. } elseif ($state === 'after') {
  2491. if (empty($results[0])) {
  2492. return array();
  2493. }
  2494. return $results[0];
  2495. }
  2496. }
  2497. /**
  2498. * Handles the before/after filter logic for find('count') operations. Only called by Model::find().
  2499. *
  2500. * @param string $state Either "before" or "after"
  2501. * @param array $query
  2502. * @param array $results
  2503. * @return integer The number of records found, or false
  2504. * @see Model::find()
  2505. */
  2506. protected function _findCount($state, $query, $results = array()) {
  2507. if ($state === 'before') {
  2508. if (!empty($query['type']) && isset($this->findMethods[$query['type']]) && $query['type'] !== 'count' ) {
  2509. $query['operation'] = 'count';
  2510. $query = $this->{'_find' . ucfirst($query['type'])}('before', $query);
  2511. }
  2512. $db = $this->getDataSource();
  2513. $query['order'] = false;
  2514. if (!method_exists($db, 'calculate')) {
  2515. return $query;
  2516. }
  2517. if (!empty($query['fields']) && is_array($query['fields'])) {
  2518. if (!preg_match('/^count/i', current($query['fields']))) {
  2519. unset($query['fields']);
  2520. }
  2521. }
  2522. if (empty($query['fields'])) {
  2523. $query['fields'] = $db->calculate($this, 'count');
  2524. } elseif (method_exists($db, 'expression') && is_string($query['fields']) && !preg_match('/count/i', $query['fields'])) {
  2525. $query['fields'] = $db->calculate($this, 'count', array(
  2526. $db->expression($query['fields']), 'count'
  2527. ));
  2528. }
  2529. return $query;
  2530. } elseif ($state === 'after') {
  2531. foreach (array(0, $this->alias) as $key) {
  2532. if (isset($results[0][$key]['count'])) {
  2533. if ($query['group']) {
  2534. return count($results);
  2535. } else {
  2536. return intval($results[0][$key]['count']);
  2537. }
  2538. }
  2539. }
  2540. return false;
  2541. }
  2542. }
  2543. /**
  2544. * Handles the before/after filter logic for find('list') operations. Only called by Model::find().
  2545. *
  2546. * @param string $state Either "before" or "after"
  2547. * @param array $query
  2548. * @param array $results
  2549. * @return array Key/value pairs of primary keys/display field values of all records found
  2550. * @see Model::find()
  2551. */
  2552. protected function _findList($state, $query, $results = array()) {
  2553. if ($state === 'before') {
  2554. if (empty($query['fields'])) {
  2555. $query['fields'] = array("{$this->alias}.{$this->primaryKey}", "{$this->alias}.{$this->displayField}");
  2556. $list = array("{n}.{$this->alias}.{$this->primaryKey}", "{n}.{$this->alias}.{$this->displayField}", null);
  2557. } else {
  2558. if (!is_array($query['fields'])) {
  2559. $query['fields'] = String::tokenize($query['fields']);
  2560. }
  2561. if (count($query['fields']) === 1) {
  2562. if (strpos($query['fields'][0], '.') === false) {
  2563. $query['fields'][0] = $this->alias . '.' . $query['fields'][0];
  2564. }
  2565. $list = array("{n}.{$this->alias}.{$this->primaryKey}", '{n}.' . $query['fields'][0], null);
  2566. $query['fields'] = array("{$this->alias}.{$this->primaryKey}", $query['fields'][0]);
  2567. } elseif (count($query['fields']) === 3) {
  2568. for ($i = 0; $i < 3; $i++) {
  2569. if (strpos($query['fields'][$i], '.') === false) {
  2570. $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
  2571. }
  2572. }
  2573. $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], '{n}.' . $query['fields'][2]);
  2574. } else {
  2575. for ($i = 0; $i < 2; $i++) {
  2576. if (strpos($query['fields'][$i], '.') === false) {
  2577. $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
  2578. }
  2579. }
  2580. $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], null);
  2581. }
  2582. }
  2583. if (!isset($query['recursive']) || $query['recursive'] === null) {
  2584. $query['recursive'] = -1;
  2585. }
  2586. list($query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']) = $list;
  2587. return $query;
  2588. } elseif ($state === 'after') {
  2589. if (empty($results)) {
  2590. return array();
  2591. }
  2592. $lst = $query['list'];
  2593. return Hash::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath']);
  2594. }
  2595. }
  2596. /**
  2597. * Detects the previous field's value, then uses logic to find the 'wrapping'
  2598. * rows and return them.
  2599. *
  2600. * @param string $state Either "before" or "after"
  2601. * @param array $query
  2602. * @param array $results
  2603. * @return array
  2604. */
  2605. protected function _findNeighbors($state, $query, $results = array()) {
  2606. if ($state === 'before') {
  2607. extract($query);
  2608. $conditions = (array)$conditions;
  2609. if (isset($field) && isset($value)) {
  2610. if (strpos($field, '.') === false) {
  2611. $field = $this->alias . '.' . $field;
  2612. }
  2613. } else {
  2614. $field = $this->alias . '.' . $this->primaryKey;
  2615. $value = $this->id;
  2616. }
  2617. $query['conditions'] = array_merge($conditions, array($field . ' <' => $value));
  2618. $query['order'] = $field . ' DESC';
  2619. $query['limit'] = 1;
  2620. $query['field'] = $field;
  2621. $query['value'] = $value;
  2622. return $query;
  2623. } elseif ($state === 'after') {
  2624. extract($query);
  2625. unset($query['conditions'][$field . ' <']);
  2626. $return = array();
  2627. if (isset($results[0])) {
  2628. $prevVal = Hash::get($results[0], $field);
  2629. $query['conditions'][$field . ' >='] = $prevVal;
  2630. $query['conditions'][$field . ' !='] = $value;
  2631. $query['limit'] = 2;
  2632. } else {
  2633. $return['prev'] = null;
  2634. $query['conditions'][$field . ' >'] = $value;
  2635. $query['limit'] = 1;
  2636. }
  2637. $query['order'] = $field . ' ASC';
  2638. $neighbors = $this->find('all', $query);
  2639. if (!array_key_exists('prev', $return)) {
  2640. $return['prev'] = isset($neighbors[0]) ? $neighbors[0] : null;
  2641. }
  2642. if (count($neighbors) === 2) {
  2643. $return['next'] = $neighbors[1];
  2644. } elseif (count($neighbors) === 1 && !$return['prev']) {
  2645. $return['next'] = $neighbors[0];
  2646. } else {
  2647. $return['next'] = null;
  2648. }
  2649. return $return;
  2650. }
  2651. }
  2652. /**
  2653. * In the event of ambiguous results returned (multiple top level results, with different parent_ids)
  2654. * top level results with different parent_ids to the first result will be dropped
  2655. *
  2656. * @param string $state
  2657. * @param mixed $query
  2658. * @param array $results
  2659. * @return array Threaded results
  2660. */
  2661. protected function _findThreaded($state, $query, $results = array()) {
  2662. if ($state === 'before') {
  2663. return $query;
  2664. } elseif ($state === 'after') {
  2665. $parent = 'parent_id';
  2666. if (isset($query['parent'])) {
  2667. $parent = $query['parent'];
  2668. }
  2669. return Hash::nest($results, array(
  2670. 'idPath' => '{n}.' . $this->alias . '.' . $this->primaryKey,
  2671. 'parentPath' => '{n}.' . $this->alias . '.' . $parent
  2672. ));
  2673. }
  2674. }
  2675. /**
  2676. * Passes query results through model and behavior afterFilter() methods.
  2677. *
  2678. * @param array $results Results to filter
  2679. * @param boolean $primary If this is the primary model results (results from model where the find operation was performed)
  2680. * @return array Set of filtered results
  2681. */
  2682. protected function _filterResults($results, $primary = true) {
  2683. $event = new CakeEvent('Model.afterFind', $this, array($results, $primary));
  2684. $event->modParams = 0;
  2685. $this->getEventManager()->dispatch($event);
  2686. return $event->result;
  2687. }
  2688. /**
  2689. * This resets the association arrays for the model back
  2690. * to those originally defined in the model. Normally called at the end
  2691. * of each call to Model::find()
  2692. *
  2693. * @return boolean Success
  2694. */
  2695. public function resetAssociations() {
  2696. if (!empty($this->__backAssociation)) {
  2697. foreach ($this->_associations as $type) {
  2698. if (isset($this->__backAssociation[$type])) {
  2699. $this->{$type} = $this->__backAssociation[$type];
  2700. }
  2701. }
  2702. $this->__backAssociation = array();
  2703. }
  2704. foreach ($this->_associations as $type) {
  2705. foreach ($this->{$type} as $key => $name) {
  2706. if (property_exists($this, $key) && !empty($this->{$key}->__backAssociation)) {
  2707. $this->{$key}->resetAssociations();
  2708. }
  2709. }
  2710. }
  2711. $this->__backAssociation = array();
  2712. return true;
  2713. }
  2714. /**
  2715. * Returns false if any fields passed match any (by default, all if $or = false) of their matching values.
  2716. *
  2717. * @param array $fields Field/value pairs to search (if no values specified, they are pulled from $this->data)
  2718. * @param boolean $or If false, all fields specified must match in order for a false return value
  2719. * @return boolean False if any records matching any fields are found
  2720. */
  2721. public function isUnique($fields, $or = true) {
  2722. if (!is_array($fields)) {
  2723. $fields = func_get_args();
  2724. if (is_bool($fields[count($fields) - 1])) {
  2725. $or = $fields[count($fields) - 1];
  2726. unset($fields[count($fields) - 1]);
  2727. }
  2728. }
  2729. foreach ($fields as $field => $value) {
  2730. if (is_numeric($field)) {
  2731. unset($fields[$field]);
  2732. $field = $value;
  2733. if (isset($this->data[$this->alias][$field])) {
  2734. $value = $this->data[$this->alias][$field];
  2735. } else {
  2736. $value = null;
  2737. }
  2738. }
  2739. if (strpos($field, '.') === false) {
  2740. unset($fields[$field]);
  2741. $fields[$this->alias . '.' . $field] = $value;
  2742. }
  2743. }
  2744. if ($or) {
  2745. $fields = array('or' => $fields);
  2746. }
  2747. if (!empty($this->id)) {
  2748. $fields[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id;
  2749. }
  2750. return ($this->find('count', array('conditions' => $fields, 'recursive' => -1)) == 0);
  2751. }
  2752. /**
  2753. * Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method.
  2754. *
  2755. * @param string $sql,... SQL statement
  2756. * @return mixed Resultset array or boolean indicating success / failure depending on the query executed
  2757. * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-query
  2758. */
  2759. public function query($sql) {
  2760. $params = func_get_args();
  2761. $db = $this->getDataSource();
  2762. return call_user_func_array(array(&$db, 'query'), $params);
  2763. }
  2764. /**
  2765. * Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations
  2766. * that use the 'with' key as well. Since _saveMulti is incapable of exiting a save operation.
  2767. *
  2768. * Will validate the currently set data. Use Model::set() or Model::create() to set the active data.
  2769. *
  2770. * @param array $options An optional array of custom options to be made available in the beforeValidate callback
  2771. * @return boolean True if there are no errors
  2772. */
  2773. public function validates($options = array()) {
  2774. return $this->validator()->validates($options);
  2775. }
  2776. /**
  2777. * Returns an array of fields that have failed validation. On the current model.
  2778. *
  2779. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  2780. * @return array Array of invalid fields
  2781. * @see Model::validates()
  2782. */
  2783. public function invalidFields($options = array()) {
  2784. return $this->validator()->errors($options);
  2785. }
  2786. /**
  2787. * Marks a field as invalid, optionally setting the name of validation
  2788. * rule (in case of multiple validation for field) that was broken.
  2789. *
  2790. * @param string $field The name of the field to invalidate
  2791. * @param mixed $value Name of validation rule that was not failed, or validation message to
  2792. * be returned. If no validation key is provided, defaults to true.
  2793. * @return void
  2794. */
  2795. public function invalidate($field, $value = true) {
  2796. $this->validator()->invalidate($field, $value);
  2797. }
  2798. /**
  2799. * Returns true if given field name is a foreign key in this model.
  2800. *
  2801. * @param string $field Returns true if the input string ends in "_id"
  2802. * @return boolean True if the field is a foreign key listed in the belongsTo array.
  2803. */
  2804. public function isForeignKey($field) {
  2805. $foreignKeys = array();
  2806. if (!empty($this->belongsTo)) {
  2807. foreach ($this->belongsTo as $data) {
  2808. $foreignKeys[] = $data['foreignKey'];
  2809. }
  2810. }
  2811. return in_array($field, $foreignKeys);
  2812. }
  2813. /**
  2814. * Escapes the field name and prepends the model name. Escaping is done according to the
  2815. * current database driver's rules.
  2816. *
  2817. * @param string $field Field to escape (e.g: id)
  2818. * @param string $alias Alias for the model (e.g: Post)
  2819. * @return string The name of the escaped field for this Model (i.e. id becomes `Post`.`id`).
  2820. */
  2821. public function escapeField($field = null, $alias = null) {
  2822. if (empty($alias)) {
  2823. $alias = $this->alias;
  2824. }
  2825. if (empty($field)) {
  2826. $field = $this->primaryKey;
  2827. }
  2828. $db = $this->getDataSource();
  2829. if (strpos($field, $db->name($alias) . '.') === 0) {
  2830. return $field;
  2831. }
  2832. return $db->name($alias . '.' . $field);
  2833. }
  2834. /**
  2835. * Returns the current record's ID
  2836. *
  2837. * @param integer $list Index on which the composed ID is located
  2838. * @return mixed The ID of the current record, false if no ID
  2839. */
  2840. public function getID($list = 0) {
  2841. if (empty($this->id) || (is_array($this->id) && isset($this->id[0]) && empty($this->id[0]))) {
  2842. return false;
  2843. }
  2844. if (!is_array($this->id)) {
  2845. return $this->id;
  2846. }
  2847. if (isset($this->id[$list]) && !empty($this->id[$list])) {
  2848. return $this->id[$list];
  2849. } elseif (isset($this->id[$list])) {
  2850. return false;
  2851. }
  2852. return current($this->id);
  2853. }
  2854. /**
  2855. * Returns the ID of the last record this model inserted.
  2856. *
  2857. * @return mixed Last inserted ID
  2858. */
  2859. public function getLastInsertID() {
  2860. return $this->getInsertID();
  2861. }
  2862. /**
  2863. * Returns the ID of the last record this model inserted.
  2864. *
  2865. * @return mixed Last inserted ID
  2866. */
  2867. public function getInsertID() {
  2868. return $this->_insertID;
  2869. }
  2870. /**
  2871. * Sets the ID of the last record this model inserted
  2872. *
  2873. * @param integer|string $id Last inserted ID
  2874. * @return void
  2875. */
  2876. public function setInsertID($id) {
  2877. $this->_insertID = $id;
  2878. }
  2879. /**
  2880. * Returns the number of rows returned from the last query.
  2881. *
  2882. * @return integer Number of rows
  2883. */
  2884. public function getNumRows() {
  2885. return $this->getDataSource()->lastNumRows();
  2886. }
  2887. /**
  2888. * Returns the number of rows affected by the last query.
  2889. *
  2890. * @return integer Number of rows
  2891. */
  2892. public function getAffectedRows() {
  2893. return $this->getDataSource()->lastAffected();
  2894. }
  2895. /**
  2896. * Sets the DataSource to which this model is bound.
  2897. *
  2898. * @param string $dataSource The name of the DataSource, as defined in app/Config/database.php
  2899. * @return void
  2900. * @throws MissingConnectionException
  2901. */
  2902. public function setDataSource($dataSource = null) {
  2903. $oldConfig = $this->useDbConfig;
  2904. if ($dataSource != null) {
  2905. $this->useDbConfig = $dataSource;
  2906. }
  2907. $db = ConnectionManager::getDataSource($this->useDbConfig);
  2908. if (!empty($oldConfig) && isset($db->config['prefix'])) {
  2909. $oldDb = ConnectionManager::getDataSource($oldConfig);
  2910. if (!isset($this->tablePrefix) || (!isset($oldDb->config['prefix']) || $this->tablePrefix == $oldDb->config['prefix'])) {
  2911. $this->tablePrefix = $db->config['prefix'];
  2912. }
  2913. } elseif (isset($db->config['prefix'])) {
  2914. $this->tablePrefix = $db->config['prefix'];
  2915. }
  2916. $this->schemaName = $db->getSchemaName();
  2917. }
  2918. /**
  2919. * Gets the DataSource to which this model is bound.
  2920. *
  2921. * @return DataSource A DataSource object
  2922. */
  2923. public function getDataSource() {
  2924. if (!$this->_sourceConfigured && $this->useTable !== false) {
  2925. $this->_sourceConfigured = true;
  2926. $this->setSource($this->useTable);
  2927. }
  2928. return ConnectionManager::getDataSource($this->useDbConfig);
  2929. }
  2930. /**
  2931. * Get associations
  2932. *
  2933. * @return array
  2934. */
  2935. public function associations() {
  2936. return $this->_associations;
  2937. }
  2938. /**
  2939. * Gets all the models with which this model is associated.
  2940. *
  2941. * @param string $type Only result associations of this type
  2942. * @return array Associations
  2943. */
  2944. public function getAssociated($type = null) {
  2945. if ($type == null) {
  2946. $associated = array();
  2947. foreach ($this->_associations as $assoc) {
  2948. if (!empty($this->{$assoc})) {
  2949. $models = array_keys($this->{$assoc});
  2950. foreach ($models as $m) {
  2951. $associated[$m] = $assoc;
  2952. }
  2953. }
  2954. }
  2955. return $associated;
  2956. } elseif (in_array($type, $this->_associations)) {
  2957. if (empty($this->{$type})) {
  2958. return array();
  2959. }
  2960. return array_keys($this->{$type});
  2961. } else {
  2962. $assoc = array_merge(
  2963. $this->hasOne,
  2964. $this->hasMany,
  2965. $this->belongsTo,
  2966. $this->hasAndBelongsToMany
  2967. );
  2968. if (array_key_exists($type, $assoc)) {
  2969. foreach ($this->_associations as $a) {
  2970. if (isset($this->{$a}[$type])) {
  2971. $assoc[$type]['association'] = $a;
  2972. break;
  2973. }
  2974. }
  2975. return $assoc[$type];
  2976. }
  2977. return null;
  2978. }
  2979. }
  2980. /**
  2981. * Gets the name and fields to be used by a join model. This allows specifying join fields
  2982. * in the association definition.
  2983. *
  2984. * @param string|array $assoc The model to be joined
  2985. * @param array $keys Any join keys which must be merged with the keys queried
  2986. * @return array
  2987. */
  2988. public function joinModel($assoc, $keys = array()) {
  2989. if (is_string($assoc)) {
  2990. list(, $assoc) = pluginSplit($assoc);
  2991. return array($assoc, array_keys($this->{$assoc}->schema()));
  2992. } elseif (is_array($assoc)) {
  2993. $with = key($assoc);
  2994. return array($with, array_unique(array_merge($assoc[$with], $keys)));
  2995. }
  2996. trigger_error(
  2997. __d('cake_dev', 'Invalid join model settings in %s. The association parameter has the wrong type, expecting a string or array, but was passed type: %s', $this->alias, gettype($assoc)),
  2998. E_USER_WARNING
  2999. );
  3000. }
  3001. /**
  3002. * Called before each find operation. Return false if you want to halt the find
  3003. * call, otherwise return the (modified) query data.
  3004. *
  3005. * @param array $queryData Data used to execute this query, i.e. conditions, order, etc.
  3006. * @return mixed true if the operation should continue, false if it should abort; or, modified
  3007. * $queryData to continue with new $queryData
  3008. * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforefind
  3009. */
  3010. public function beforeFind($queryData) {
  3011. return true;
  3012. }
  3013. /**
  3014. * Called after each find operation. Can be used to modify any results returned by find().
  3015. * Return value should be the (modified) results.
  3016. *
  3017. * @param mixed $results The results of the find operation
  3018. * @param boolean $primary Whether this model is being queried directly (vs. being queried as an association)
  3019. * @return mixed Result of the find operation
  3020. * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#afterfind
  3021. */
  3022. public function afterFind($results, $primary = false) {
  3023. return $results;
  3024. }
  3025. /**
  3026. * Called before each save operation, after validation. Return a non-true result
  3027. * to halt the save.
  3028. *
  3029. * @param array $options
  3030. * @return boolean True if the operation should continue, false if it should abort
  3031. * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforesave
  3032. */
  3033. public function beforeSave($options = array()) {
  3034. return true;
  3035. }
  3036. /**
  3037. * Called after each successful save operation.
  3038. *
  3039. * @param boolean $created True if this save created a new record
  3040. * @return void
  3041. * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#aftersave
  3042. */
  3043. public function afterSave($created) {
  3044. }
  3045. /**
  3046. * Called before every deletion operation.
  3047. *
  3048. * @param boolean $cascade If true records that depend on this record will also be deleted
  3049. * @return boolean True if the operation should continue, false if it should abort
  3050. * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforedelete
  3051. */
  3052. public function beforeDelete($cascade = true) {
  3053. return true;
  3054. }
  3055. /**
  3056. * Called after every deletion operation.
  3057. *
  3058. * @return void
  3059. * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#afterdelete
  3060. */
  3061. public function afterDelete() {
  3062. }
  3063. /**
  3064. * Called during validation operations, before validation. Please note that custom
  3065. * validation rules can be defined in $validate.
  3066. *
  3067. * @param array $options Options passed from model::save(), see $options of model::save().
  3068. * @return boolean True if validate operation should continue, false to abort
  3069. * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforevalidate
  3070. */
  3071. public function beforeValidate($options = array()) {
  3072. return true;
  3073. }
  3074. /**
  3075. * Called after data has been checked for errors
  3076. *
  3077. * @return void
  3078. */
  3079. public function afterValidate() {
  3080. }
  3081. /**
  3082. * Called when a DataSource-level error occurs.
  3083. *
  3084. * @return void
  3085. * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#onerror
  3086. */
  3087. public function onError() {
  3088. }
  3089. /**
  3090. * Clears cache for this model.
  3091. *
  3092. * @param string $type If null this deletes cached views if Cache.check is true
  3093. * Will be used to allow deleting query cache also
  3094. * @return boolean true on delete
  3095. */
  3096. protected function _clearCache($type = null) {
  3097. if ($type === null) {
  3098. if (Configure::read('Cache.check') === true) {
  3099. $assoc[] = strtolower(Inflector::pluralize($this->alias));
  3100. $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($this->alias)));
  3101. foreach ($this->_associations as $key => $association) {
  3102. foreach ($this->$association as $key => $className) {
  3103. $check = strtolower(Inflector::pluralize($className['className']));
  3104. if (!in_array($check, $assoc)) {
  3105. $assoc[] = strtolower(Inflector::pluralize($className['className']));
  3106. $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($className['className'])));
  3107. }
  3108. }
  3109. }
  3110. clearCache($assoc);
  3111. return true;
  3112. }
  3113. } else {
  3114. //Will use for query cache deleting
  3115. }
  3116. }
  3117. /**
  3118. * Retunrs an instance of a model validator for this class
  3119. *
  3120. * @return ModelValidator
  3121. */
  3122. public function validator($instance = null) {
  3123. if ($instance instanceof ModelValidator) {
  3124. return $this->_validator = $instance;
  3125. }
  3126. if (empty($this->_validator) && is_null($instance)) {
  3127. $this->_validator = new ModelValidator($this);
  3128. }
  3129. return $this->_validator;
  3130. }
  3131. }