ResetBehavior.php 2.0 KB

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