ResetBehavior.php 5.0 KB

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