ResetBehavior.php 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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. * 2011-12-06 ms
  31. */
  32. class ResetBehavior extends ModelBehavior {
  33. protected $_defaults = array(
  34. 'limit' => 100, // batch of records per loop
  35. 'timeout' => null, // in seconds
  36. 'fields' => array(), // if not displayField
  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. * resetRecords method
  57. *
  58. * Regenerate all records (run beforeValidate/beforeSave callbacks).
  59. *
  60. * @param Model $Model
  61. * @param array $conditions
  62. * @param integer $recursive
  63. * @return bool true on success false otherwise
  64. */
  65. public function resetRecords(Model $Model, $params = array()) {
  66. $recursive = -1;
  67. extract($this->settings[$Model->alias]);
  68. $defaults = array(
  69. 'page' => 1,
  70. 'limit' => $limit,
  71. 'fields' => array(),
  72. 'order' => $Model->alias.'.'.$Model->displayField . ' ASC',
  73. 'conditions' => $scope,
  74. 'recursive' => $recursive,
  75. );
  76. if (!empty($fields)) {
  77. if (!$Model->hasField($fields)) {
  78. throw new CakeException('Model does not have fields ' . print_r($fields, true));
  79. }
  80. $defaults['fields'] = array_merge(array($Model->primaryKey), $fields);
  81. } else {
  82. $defaults['fields'] = array($Model->primaryKey);
  83. if ($Model->displayField !== $Model->primaryKey) {
  84. $defaults['fields'][] = $Model->displayField;
  85. }
  86. }
  87. if (!$updateTimestamp) {
  88. $fields = array('modified', 'updated');
  89. foreach ($fields as $field) {
  90. if ($Model->schema($field)) {
  91. $defaults['fields'][] = $field;
  92. break;
  93. }
  94. }
  95. }
  96. $params = array_merge($defaults, $params);
  97. $count = $Model->find('count', compact('conditions'));
  98. $max = ini_get('max_execution_time');
  99. if ($max) {
  100. set_time_limit (max($max, $count / $limit));
  101. }
  102. while ($rows = $Model->find('all', $params)) {
  103. foreach ($rows as $row) {
  104. $Model->create();
  105. $fields = $params['fields'];
  106. if ($callback) {
  107. $Model->{$callback}($row, $fields);
  108. }
  109. $res = $Model->save($row, $validate, $fields);
  110. if (!$res) {
  111. throw new CakeException(print_r($Model->validationErrors, true));
  112. }
  113. }
  114. $params['page']++;
  115. if ($timeout) {
  116. sleep((int)$timeout);
  117. }
  118. }
  119. return true;
  120. }
  121. }