/Model/Behavior/SoftDeleteBehavior.php

https://github.com/sams/utils · PHP · 334 lines · 195 code · 28 blank · 111 comment · 37 complexity · d6364e37df8961056bb62e3b06e09200 MD5 · raw file

  1. <?php
  2. /**
  3. * Copyright 2007-2010, Cake Development Corporation (http://cakedc.com)
  4. *
  5. * Licensed under The MIT License
  6. * Redistributions of files must retain the above copyright notice.
  7. *
  8. * @copyright Copyright 2007-2010, Cake Development Corporation (http://cakedc.com)
  9. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  10. */
  11. App::uses('ModelBehavior', 'Model');
  12. /**
  13. * Utils Plugin
  14. *
  15. * Utils Soft Delete Behavior
  16. *
  17. * @package utils
  18. * @subpackage utils.models.behaviors
  19. */
  20. class SoftDeleteBehavior extends ModelBehavior {
  21. /**
  22. * Default settings
  23. *
  24. * @var array $default
  25. */
  26. public $default = array('deleted' => 'deleted_date');
  27. /**
  28. * Holds activity flags for models
  29. *
  30. * @var array $runtime
  31. */
  32. public $runtime = array();
  33. /**
  34. * Setup callback
  35. *
  36. * @param object $model
  37. * @param array $settings
  38. */
  39. public function setup(&$model, $settings = array()) {
  40. if (empty($settings)) {
  41. $settings = $this->default;
  42. } elseif (!is_array($settings)) {
  43. $settings = array($settings);
  44. }
  45. $error = 'SoftDeleteBehavior::setup(): model ' . $model->alias . ' has no field ';
  46. $fields = $this->_normalizeFields($model, $settings);
  47. foreach ($fields as $flag => $date) {
  48. if ($model->hasField($flag)) {
  49. if ($date && !$model->hasField($date)) {
  50. trigger_error($error . $date, E_USER_NOTICE);
  51. return;
  52. }
  53. continue;
  54. }
  55. trigger_error($error . $flag, E_USER_NOTICE);
  56. return;
  57. }
  58. $this->settings[$model->alias] = $fields;
  59. $this->softDelete($model, true);
  60. }
  61. /**
  62. * Before find callback
  63. *
  64. * @param object $model
  65. * @param array $query
  66. * @return array
  67. */
  68. public function beforeFind(&$model, $query) {
  69. $runtime = $this->runtime[$model->alias];
  70. if ($runtime) {
  71. if (!is_array($query['conditions'])) {
  72. $query['conditions'] = array();
  73. }
  74. $conditions = array_filter(array_keys($query['conditions']));
  75. $fields = $this->_normalizeFields($model);
  76. foreach ($fields as $flag => $date) {
  77. if (true === $runtime || $flag === $runtime) {
  78. if (!in_array($flag, $conditions) && !in_array($model->name . '.' . $flag, $conditions)) {
  79. $query['conditions'][$model->alias . '.' . $flag] = false;
  80. }
  81. if ($flag === $runtime) {
  82. break;
  83. }
  84. }
  85. }
  86. return $query;
  87. }
  88. }
  89. /**
  90. * Before delete callback
  91. *
  92. * @param object $model
  93. * @param array $query
  94. * @return boolean
  95. */
  96. public function beforeDelete(&$model) {
  97. $runtime = $this->runtime[$model->alias];
  98. if ($runtime) {
  99. $this->delete($model, $model->id);
  100. return false;
  101. }
  102. }
  103. /**
  104. * Mark record as deleted
  105. *
  106. * @param object $model
  107. * @param integer $id
  108. * @return boolean
  109. */
  110. public function delete(&$model, $id) {
  111. $runtime = $this->runtime[$model->alias];
  112. $data = array();
  113. $fields = $this->_normalizeFields($model);
  114. foreach ($fields as $flag => $date) {
  115. if (true === $runtime || $flag === $runtime) {
  116. $data[$flag] = true;
  117. if ($date) {
  118. $data[$date] = date('Y-m-d H:i:s');
  119. }
  120. if ($flag === $runtime) {
  121. break;
  122. }
  123. }
  124. }
  125. $model->create();
  126. $model->set($model->primaryKey, $id);
  127. return $model->save(array($model->alias => $data), false, array_keys($data));
  128. }
  129. /**
  130. * Mark record as not deleted
  131. *
  132. * @param object $model
  133. * @param integer $id
  134. * @return boolean
  135. */
  136. public function undelete(&$model, $id) {
  137. $runtime = $this->runtime[$model->alias];
  138. $this->softDelete($model, false);
  139. $data = array();
  140. $fields = $this->_normalizeFields($model);
  141. foreach ($fields as $flag => $date) {
  142. if (true === $runtime || $flag === $runtime) {
  143. $data[$flag] = false;
  144. if ($date) {
  145. $data[$date] = null;
  146. }
  147. if ($flag === $runtime) {
  148. break;
  149. }
  150. }
  151. }
  152. $model->create();
  153. $model->set($model->primaryKey, $id);
  154. $result = $model->save(array($model->alias => $data), false, array_keys($data));
  155. $this->softDelete($model, $runtime);
  156. return $result;
  157. }
  158. /**
  159. * Enable/disable SoftDelete functionality
  160. *
  161. * Usage from model:
  162. * $this->softDelete(false); deactivate this behavior for model
  163. * $this->softDelete('field_two'); enabled only for this flag field
  164. * $this->softDelete(true); enable again for all flag fields
  165. * $config = $this->softDelete(null); for obtaining current setting
  166. *
  167. * @param object $model
  168. * @param mixed $active
  169. * @return mixed if $active is null, then current setting/null, or boolean if runtime setting for model was changed
  170. */
  171. public function softDelete(&$model, $active) {
  172. if (is_null($active)) {
  173. return !empty($this->runtime[$model->alias]) ? @$this->runtime[$model->alias] : null;
  174. }
  175. $result = !isset($this->runtime[$model->alias]) || $this->runtime[$model->alias] !== $active;
  176. $this->runtime[$model->alias] = $active;
  177. $this->_softDeleteAssociations($model, $active);
  178. return $result;
  179. }
  180. /**
  181. * Returns number of outdated softdeleted records prepared for purge
  182. *
  183. * @param object $model
  184. * @param mixed $expiration anything parseable by strtotime(), by default '-90 days'
  185. * @return integer
  186. */
  187. public function purgeDeletedCount(&$model, $expiration = '-90 days') {
  188. $this->softDelete($model, false);
  189. return $model->find('count', array(
  190. 'conditions' => $this->_purgeDeletedConditions($model, $expiration),
  191. 'recursive' => -1));
  192. }
  193. /**
  194. * Purge table
  195. *
  196. * @param object $model
  197. * @param mixed $expiration anything parseable by strtotime(), by default '-90 days'
  198. * @return boolean if there were some outdated records
  199. */
  200. public function purgeDeleted(&$model, $expiration = '-90 days') {
  201. $this->softDelete($model, false);
  202. $records = $model->find('all', array(
  203. 'conditions' => $this->_purgeDeletedConditions($model, $expiration),
  204. 'fields' => array($model->primaryKey),
  205. 'recursive' => -1));
  206. if ($records) {
  207. foreach ($records as $record) {
  208. $model->delete($record[$model->alias][$model->primaryKey]);
  209. }
  210. return true;
  211. }
  212. return false;
  213. }
  214. /**
  215. * Returns conditions for finding outdated records
  216. *
  217. * @param object $model
  218. * @param mixed $expiration anything parseable by strtotime(), by default '-90 days'
  219. * @return array
  220. */
  221. protected function _purgeDeletedConditions(&$model, $expiration = '-90 days') {
  222. $purgeDate = date('Y-m-d H:i:s', strtotime($expiration));
  223. $conditions = array();
  224. foreach ($this->settings[$model->alias] as $flag => $date) {
  225. $conditions[$model->alias . '.' . $flag] = true;
  226. if ($date) {
  227. $conditions[$model->alias . '.' . $date . ' <'] = $purgeDate;
  228. }
  229. }
  230. return $conditions;
  231. }
  232. /**
  233. * Return normalized field array
  234. *
  235. * @param object $model
  236. * @param array $settings
  237. * @return array
  238. */
  239. protected function _normalizeFields(&$model, $settings = array()) {
  240. if (empty($settings)) {
  241. $settings = @$this->settings[$model->alias];
  242. }
  243. $result = array();
  244. foreach ($settings as $flag => $date) {
  245. if (is_numeric($flag)) {
  246. $flag = $date;
  247. $date = false;
  248. }
  249. $result[$flag] = $date;
  250. }
  251. return $result;
  252. }
  253. /**
  254. * Modifies conditions of hasOne and hasMany associations
  255. *
  256. * If multiple delete flags are configured for model, then $active=true doesn't
  257. * do anything - you have to alter conditions in association definition
  258. *
  259. * @param object $model
  260. * @param mixed $active
  261. */
  262. protected function _softDeleteAssociations(&$model, $active) {
  263. if (empty($model->belongsTo)) {
  264. return;
  265. }
  266. $fields = array_keys($this->_normalizeFields($model));
  267. $parentModels = array_keys($model->belongsTo);
  268. foreach ($parentModels as $parentModel) {
  269. foreach (array('hasOne', 'hasMany') as $assocType) {
  270. if (empty($model->{$parentModel}->{$assocType})) {
  271. continue;
  272. }
  273. foreach ($model->{$parentModel}->{$assocType} as $assoc => $assocConfig) {
  274. $modelName = !empty($assocConfig['className']) ? $assoc : @$assocConfig['className'];
  275. if ($model->alias != $modelName) {
  276. continue;
  277. }
  278. $conditions =& $model->{$parentModel}->{$assocType}[$assoc]['conditions'];
  279. if (!is_array($conditions)) {
  280. $model->{$parentModel}->{$assocType}[$assoc]['conditions'] = array();
  281. }
  282. $multiFields = 1 < count($fields);
  283. foreach ($fields as $field) {
  284. if ($active) {
  285. if (!isset($conditions[$field]) && !isset($conditions[$assoc . '.' . $field])) {
  286. if (is_string($active)) {
  287. if ($field == $active) {
  288. $conditions[$assoc . '.' . $field] = false;
  289. }
  290. elseif (isset($conditions[$assoc . '.' . $field])) {
  291. unset($conditions[$assoc . '.' . $field]);
  292. }
  293. }
  294. elseif (!$multiFields) {
  295. $conditions[$assoc . '.' . $field] = false;
  296. }
  297. }
  298. } elseif (isset($conditions[$assoc . '.' . $field])) {
  299. unset($conditions[$assoc . '.' . $field]);
  300. }
  301. }
  302. }
  303. }
  304. }
  305. }
  306. }