ResetBehavior.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. * @author Mark Scherer
  9. * @license MIT
  10. * @cakephp 2.0
  11. * @version 1
  12. * 2011-12-06 ms
  13. */
  14. class ResetBehavior extends ModelBehavior {
  15. protected $_defaults = array(
  16. 'limit' => 100,
  17. 'auto' => false,
  18. 'fields' => array(),
  19. 'model' => null,
  20. 'notices' => true,
  21. 'validate' => true,
  22. );
  23. /**
  24. * Configure the behavior through the Model::actsAs property
  25. *
  26. * @param object $Model
  27. * @param array $config
  28. */
  29. public function setup(Model $Model, $config = null) {
  30. if (is_array($config)) {
  31. $this->settings[$Model->alias] = array_merge($this->_defaults, $config);
  32. } else {
  33. $this->settings[$Model->alias] = $this->_defaults;
  34. }
  35. }
  36. /**
  37. * resetRecords method
  38. *
  39. * Regenerate all records (run beforeValidate/beforeSave callbacks).
  40. *
  41. * @param Model $Model
  42. * @param array $conditions
  43. * @param int $recursive
  44. * @return bool true on success false otherwise
  45. */
  46. public function resetRecords(Model $Model, $params = array()) {
  47. $recursive = -1;
  48. extract($this->settings[$Model->alias]);
  49. /*
  50. if ($notices && !$Model->hasField($fields)) {
  51. return false;
  52. }
  53. */
  54. $defaults = array(
  55. 'page' => 1,
  56. 'limit' => $limit,
  57. 'fields' => array(),
  58. 'order' => $Model->alias.'.'.$Model->displayField . ' ASC',
  59. 'conditions' => array(),
  60. 'recursive' => $recursive,
  61. );
  62. if (!empty($fields)) {
  63. $defaults['fields'] = array_merge(array($Model->primaryKey), $fields);
  64. } else {
  65. $defaults['fields'] = array($Model->primaryKey, $Model->displayField);
  66. }
  67. $params = array_merge($defaults, $params);
  68. $count = $Model->find('count', compact('conditions'));
  69. $max = ini_get('max_execution_time');
  70. if ($max) {
  71. set_time_limit (max($max, $count / $limit));
  72. }
  73. while ($rows = $Model->find('all', $params)) {
  74. foreach ($rows as $row) {
  75. $Model->create();
  76. $res = $Model->save($row, $validate, $params['fields']);
  77. if (!$res) {
  78. throw new CakeException(print_r($Model->validationErrors, true));
  79. }
  80. }
  81. $params['page']++;
  82. }
  83. return true;
  84. }
  85. }