ResetBehavior.php 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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. * For tables with lots of records you might want to use a shell and the CLI to invoke the reset/update process.
  25. *
  26. * @author Mark Scherer
  27. * @license MIT
  28. * @cakephp 2.x
  29. * @version 1.0
  30. */
  31. class ResetBehavior extends ModelBehavior {
  32. protected $_defaults = array(
  33. 'limit' => 100, // batch of records per loop
  34. 'timeout' => null, // in seconds
  35. 'fields' => array(), // if not displayField
  36. 'updateFields' => array(), // if saved fields should be different from fields
  37. 'validate' => true, // trigger beforeValidate callback
  38. 'updateTimestamp' => false, // update modified/updated timestamp
  39. 'scope' => array(), // optional conditions
  40. 'callback' => null,
  41. );
  42. /**
  43. * Configure the behavior through the Model::actsAs property
  44. *
  45. * @param object $Model
  46. * @param array $config
  47. */
  48. public function setup(Model $Model, $config = null) {
  49. if (is_array($config)) {
  50. $this->settings[$Model->alias] = array_merge($this->_defaults, $config);
  51. } else {
  52. $this->settings[$Model->alias] = $this->_defaults;
  53. }
  54. }
  55. /**
  56. * Regenerate all records (including possible beforeValidate/beforeSave callbacks).
  57. *
  58. * @param Model $Model
  59. * @param array $conditions
  60. * @param integer $recursive
  61. * @return integer Modified records
  62. */
  63. public function resetRecords(Model $Model, $params = array()) {
  64. $recursive = -1;
  65. extract($this->settings[$Model->alias]);
  66. $defaults = array(
  67. 'page' => 1,
  68. 'limit' => $limit,
  69. 'fields' => array(),
  70. 'order' => $Model->alias . '.' . $Model->primaryKey . ' ASC',
  71. 'conditions' => $scope,
  72. 'recursive' => $recursive,
  73. );
  74. if (!empty($fields)) {
  75. if (!$Model->hasField($fields)) {
  76. throw new CakeException('Model does not have fields ' . print_r($fields, true));
  77. }
  78. $defaults['fields'] = array_merge(array($Model->primaryKey), $fields);
  79. } else {
  80. $defaults['fields'] = array($Model->primaryKey);
  81. if ($Model->displayField !== $Model->primaryKey) {
  82. $defaults['fields'][] = $Model->displayField;
  83. }
  84. }
  85. if (!$updateTimestamp) {
  86. $fields = array('modified', 'updated');
  87. foreach ($fields as $field) {
  88. if ($Model->schema($field)) {
  89. $defaults['fields'][] = $field;
  90. break;
  91. }
  92. }
  93. }
  94. $params = array_merge($defaults, $params);
  95. $count = $Model->find('count', compact('conditions'));
  96. $max = ini_get('max_execution_time');
  97. if ($max) {
  98. set_time_limit(max($max, $count / $limit));
  99. }
  100. $modifed = 0;
  101. while ($rows = $Model->find('all', $params)) {
  102. foreach ($rows as $row) {
  103. $Model->create();
  104. $fields = $params['fields'];
  105. if (!empty($updateFields)) {
  106. $fields = $updateFields;
  107. }
  108. if ($fields && !in_array($Model->primaryKey, $fields)) {
  109. $fields[] = $Model->primaryKey;
  110. }
  111. if ($callback) {
  112. if (is_callable($callback)) {
  113. $parameters = array(&$row, &$fields);
  114. $row = call_user_func_array($callback, $parameters);
  115. } else {
  116. $row = $Model->{$callback}($row, $fields);
  117. }
  118. if (!$row) {
  119. continue;
  120. }
  121. }
  122. $res = $Model->save($row, $validate, $fields);
  123. if (!$res) {
  124. throw new CakeException(print_r($Model->validationErrors, true));
  125. }
  126. $modifed++;
  127. }
  128. $params['page']++;
  129. if ($timeout) {
  130. sleep((int)$timeout);
  131. }
  132. }
  133. return $modifed;
  134. }
  135. }