ResetBehavior.php 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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 $_defaults = 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 = null) {
  58. if (is_array($config)) {
  59. $this->settings[$Model->alias] = array_merge($this->_defaults, $config);
  60. } else {
  61. $this->settings[$Model->alias] = $this->_defaults;
  62. }
  63. }
  64. /**
  65. * Regenerate all records (including possible beforeValidate/beforeSave callbacks).
  66. *
  67. * @param Model $Model
  68. * @param array $conditions
  69. * @param integer $recursive
  70. * @return integer Modified records
  71. */
  72. public function resetRecords(Model $Model, $params = array()) {
  73. $recursive = -1;
  74. extract($this->settings[$Model->alias]);
  75. $defaults = array(
  76. 'page' => 1,
  77. 'limit' => $limit,
  78. 'fields' => array(),
  79. 'order' => $Model->alias . '.' . $Model->primaryKey . ' ASC',
  80. 'conditions' => $scope,
  81. 'recursive' => $recursive,
  82. );
  83. if (!empty($fields)) {
  84. if (!$Model->hasField($fields)) {
  85. throw new CakeException('Model does not have fields ' . print_r($fields, true));
  86. }
  87. $defaults['fields'] = array_merge(array($Model->primaryKey), $fields);
  88. } else {
  89. $defaults['fields'] = array($Model->primaryKey);
  90. if ($Model->displayField !== $Model->primaryKey) {
  91. $defaults['fields'][] = $Model->displayField;
  92. }
  93. }
  94. if (!$updateTimestamp) {
  95. $fields = array('modified', 'updated');
  96. foreach ($fields as $field) {
  97. if ($Model->schema($field)) {
  98. $defaults['fields'][] = $field;
  99. break;
  100. }
  101. }
  102. }
  103. $params = array_merge($defaults, $params);
  104. $count = $Model->find('count', compact('conditions'));
  105. $max = ini_get('max_execution_time');
  106. if ($max) {
  107. set_time_limit(max($max, $count / $limit));
  108. }
  109. $modifed = 0;
  110. while ($rows = $Model->find('all', $params)) {
  111. foreach ($rows as $row) {
  112. $Model->create();
  113. $fieldList = $params['fields'];
  114. if (!empty($updateFields)) {
  115. $fieldList = $updateFields;
  116. }
  117. if ($fieldList && !in_array($Model->primaryKey, $fieldList)) {
  118. $fieldList[] = $Model->primaryKey;
  119. }
  120. if ($callback) {
  121. if (is_callable($callback)) {
  122. $parameters = array(&$row, &$fieldList);
  123. $row = call_user_func_array($callback, $parameters);
  124. } else {
  125. $row = $Model->{$callback}($row, $fieldList);
  126. }
  127. if (!$row) {
  128. continue;
  129. }
  130. }
  131. $res = $Model->save($row, compact('validate', 'fieldList'));
  132. if (!$res) {
  133. throw new CakeException(print_r($Model->validationErrors, true));
  134. }
  135. $modifed++;
  136. }
  137. $params['page']++;
  138. if ($timeout) {
  139. sleep((int)$timeout);
  140. }
  141. }
  142. return $modifed;
  143. }
  144. }