ResetBehavior.php 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. <?php
  2. namespace Tools\Model\Behavior;
  3. use Cake\Core\Configure;
  4. use Cake\ORM\Behavior;
  5. use Cake\ORM\Entity;
  6. use Cake\ORM\Table;
  7. /**
  8. * Allows the model to reset all records as batch command.
  9. * This way any slugging, geocoding or other beforeValidate, 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. protected $_defaultConfig = array(
  45. 'limit' => 100, // batch of records per loop
  46. 'timeout' => null, // in seconds
  47. 'fields' => array(), // if not displayField
  48. 'updateFields' => array(), // if saved fields should be different from fields
  49. 'validate' => true, // trigger beforeValidate callback
  50. 'updateTimestamp' => false, // update modified/updated timestamp
  51. 'scope' => array(), // optional conditions
  52. 'callback' => null,
  53. );
  54. /**
  55. * Adding validation rules
  56. * also adds and merges config settings (direct + configure)
  57. *
  58. * @return void
  59. */
  60. public function __construct(Table $table, array $config = []) {
  61. $defaults = $this->_defaultConfig;
  62. if ($configureDefaults = Configure::read('Reset')) {
  63. $defaults = $configureDefaults + $defaults;
  64. }
  65. $config + $defaults;
  66. parent::__construct($table, $config);
  67. }
  68. /**
  69. * Regenerate all records (including possible beforeValidate/beforeSave callbacks).
  70. *
  71. * @param Model $Model
  72. * @param array $conditions
  73. * @param int $recursive
  74. * @return int Modified records
  75. */
  76. public function resetRecords($params = array()) {
  77. $defaults = array(
  78. 'page' => 1,
  79. 'limit' => $this->_config['limit'],
  80. 'fields' => array(),
  81. 'order' => $this->_table->alias() . '.' . $this->_table->primaryKey() . ' ASC',
  82. 'conditions' => $this->_config['scope'],
  83. );
  84. if (!empty($this->_config['fields'])) {
  85. foreach ((array)$this->_config['fields'] as $field) {
  86. if (!$this->_table->hasField($field)) {
  87. throw new \Exception('Table does not have field ' . $field);
  88. }
  89. }
  90. $defaults['fields'] = array_merge(array($this->_table->alias() . '.' . $this->_table->primaryKey()), $this->_config['fields']);
  91. } else {
  92. $defaults['fields'] = array($this->_table->alias() . '.' . $this->_table->primaryKey());
  93. if ($this->_table->displayField() !== $this->_table->primaryKey()) {
  94. $defaults['fields'][] = $this->_table->alias() . '.' . $this->_table->displayField();
  95. }
  96. }
  97. if (!$this->_config['updateTimestamp']) {
  98. $fields = array('modified', 'updated');
  99. foreach ($fields as $field) {
  100. if ($this->_table->schema()->column($field)) {
  101. $defaults['fields'][] = $field;
  102. break;
  103. }
  104. }
  105. }
  106. $params += $defaults;
  107. $count = $this->_table->find('count', compact('conditions'));
  108. $max = ini_get('max_execution_time');
  109. if ($max) {
  110. set_time_limit(max($max, $count / $this->_config['limit']));
  111. }
  112. $modified = 0;
  113. while (($records = $this->_table->find('all', $params)->toArray())) {
  114. foreach ($records as $record) {
  115. $fieldList = $params['fields'];
  116. if (!empty($updateFields)) {
  117. $fieldList = $updateFields;
  118. }
  119. if ($fieldList && !in_array($this->_table->primaryKey(), $fieldList)) {
  120. $fieldList[] = $this->_table->primaryKey();
  121. }
  122. if ($this->_config['callback']) {
  123. if (is_callable($this->_config['callback'])) {
  124. $parameters = array($record, &$fieldList);
  125. $record = call_user_func_array($this->_config['callback'], $parameters);
  126. } else {
  127. $record = $this->_table->{$this->_config['callback']}($record, $fieldList);
  128. }
  129. if (!$record) {
  130. continue;
  131. }
  132. }
  133. $res = $this->_table->save($record, compact('validate', 'fieldList'));
  134. if (!$res) {
  135. throw new \Exception(print_r($this->_table->errors(), true));
  136. }
  137. $modified++;
  138. }
  139. $params['page']++;
  140. if ($this->_config['timeout']) {
  141. sleep((int)$this->_config['timeout']);
  142. }
  143. }
  144. return $modified;
  145. }
  146. }