ResetBehavior.php 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. <?php
  2. App::uses('ModelBehavior', 'Model');
  3. /**
  4. * Allows the model to reset all records as batch command.
  5. * This way any slugging, geocoding or other beforeValidate, beforeSave, ... callbacks
  6. * can be retriggered for them.
  7. *
  8. * By default it will not update the modified timestamp and will re-save id and displayName.
  9. * If you need more fields, you need to specify them manually.
  10. *
  11. * You can also disable validate callback or provide a conditions scope to match only a subset
  12. * of records.
  13. *
  14. * For performance and memory reasons the records will only be processed in loops (not all at once).
  15. * If you have time-sensitive data, you can modify the limit of records per loop as well as the
  16. * timeout in between each loop.
  17. * Remember to raise set_time_limit() if you do not run this via CLI.
  18. *
  19. * It is recommended to attach this behavior dynamically where needed:
  20. *
  21. * $this->Model->Behaviors->load('Tools.Reset', array(...));
  22. * $this->Model->resetRecords();
  23. *
  24. * If you want to provide a callback function/method, you can either use object methods or
  25. * static functions/methods:
  26. *
  27. * 'callback' => array($this, 'methodName')
  28. *
  29. * and
  30. *
  31. * public function methodName($data, &$fields) {}
  32. *
  33. * For tables with lots of records you might want to use a shell and the CLI to invoke the reset/update process.
  34. *
  35. * @author Mark Scherer
  36. * @license MIT
  37. * @cakephp 2.x
  38. * @version 1.0
  39. */
  40. class ResetBehavior extends ModelBehavior {
  41. protected $_defaultConfig = array(
  42. 'limit' => 100, // batch of records per loop
  43. 'timeout' => null, // in seconds
  44. 'fields' => array(), // if not displayField
  45. 'updateFields' => array(), // if saved fields should be different from fields
  46. 'validate' => true, // trigger beforeValidate callback
  47. 'updateTimestamp' => false, // update modified/updated timestamp
  48. 'scope' => array(), // optional conditions
  49. 'callback' => null,
  50. );
  51. /**
  52. * Configure the behavior through the Model::actsAs property
  53. *
  54. * @param object $Model
  55. * @param array $config
  56. */
  57. public function setup(Model $Model, $config = array()) {
  58. $this->settings[$Model->alias] = $config + $this->_defaultConfig;
  59. }
  60. /**
  61. * Regenerate all records (including possible beforeValidate/beforeSave callbacks).
  62. *
  63. * @param Model $Model
  64. * @param array $conditions
  65. * @param int $recursive
  66. * @return int Modified records
  67. */
  68. public function resetRecords(Model $Model, $params = array()) {
  69. $recursive = -1;
  70. extract($this->settings[$Model->alias]);
  71. $defaults = array(
  72. 'page' => 1,
  73. 'limit' => $limit,
  74. 'fields' => array(),
  75. 'order' => $Model->alias . '.' . $Model->primaryKey . ' ASC',
  76. 'conditions' => $scope,
  77. 'recursive' => $recursive,
  78. );
  79. if (!empty($fields)) {
  80. if (!$Model->hasField($fields)) {
  81. throw new CakeException('Model does not have fields ' . print_r($fields, true));
  82. }
  83. $defaults['fields'] = array_merge(array($Model->primaryKey), $fields);
  84. } else {
  85. $defaults['fields'] = array($Model->primaryKey);
  86. if ($Model->displayField !== $Model->primaryKey) {
  87. $defaults['fields'][] = $Model->displayField;
  88. }
  89. }
  90. if (!$updateTimestamp) {
  91. $fields = array('modified', 'updated');
  92. foreach ($fields as $field) {
  93. if ($Model->schema($field)) {
  94. $defaults['fields'][] = $field;
  95. break;
  96. }
  97. }
  98. }
  99. $params += $defaults;
  100. $count = $Model->find('count', compact('conditions'));
  101. $max = ini_get('max_execution_time');
  102. if ($max) {
  103. set_time_limit(max($max, $count / $limit));
  104. }
  105. $modifed = 0;
  106. while ($rows = $Model->find('all', $params)) {
  107. foreach ($rows as $row) {
  108. $Model->create();
  109. $fieldList = $params['fields'];
  110. if (!empty($updateFields)) {
  111. $fieldList = $updateFields;
  112. }
  113. if ($fieldList && !in_array($Model->primaryKey, $fieldList)) {
  114. $fieldList[] = $Model->primaryKey;
  115. }
  116. if ($callback) {
  117. if (is_callable($callback)) {
  118. $parameters = array(&$row, &$fieldList);
  119. $row = call_user_func_array($callback, $parameters);
  120. } else {
  121. $row = $Model->{$callback}($row, $fieldList);
  122. }
  123. if (!$row) {
  124. continue;
  125. }
  126. }
  127. $res = $Model->save($row, compact('validate', 'fieldList'));
  128. if (!$res) {
  129. throw new CakeException(print_r($Model->validationErrors, true));
  130. }
  131. $modifed++;
  132. }
  133. $params['page']++;
  134. if ($timeout) {
  135. sleep((int)$timeout);
  136. }
  137. }
  138. return $modifed;
  139. }
  140. }