This repository was archived by the owner on Oct 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 138
Expand file tree
/
Copy pathSoftDeleteBehavior.php
More file actions
439 lines (402 loc) · 10.9 KB
/
SoftDeleteBehavior.php
File metadata and controls
439 lines (402 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
<?php
/**
* Copyright 2009 - 2014, Cake Development Corporation (http://cakedc.com)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2009 - 2014, Cake Development Corporation (http://cakedc.com)
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Utils Plugin
*
* Utils Soft Delete Behavior
*
* @package utils
* @subpackage utils.models.behaviors
*/
class SoftDeleteBehavior extends ModelBehavior {
/**
* Default settings
*
* @var array $default
*/
public $default = array(
'deleted' => 'deleted_date',
'atomic' => true,
);
/**
* Holds activity flags for models
*
* @var array $runtime
*/
public $runtime = array();
/**
* Holds atomic flag for model save operation
*
* @var bool $_atomic
*/
protected $_atomic = true;
/**
* Setup callback
*
* @param Model $model
* @param array $settings
*/
public function setup(Model $model, $settings = array()) {
if (array_key_exists('atomic', $settings)) {
$this->_atomic = $settings['atomic'];
unset($settings['atomic']);
}
if (empty($settings)) {
$settings = $this->default;
} elseif (!is_array($settings)) {
$settings = array($settings);
}
$error = __d('utils', 'SoftDeleteBehavior::setup(): model %s has no field!', $model->name);
$fields = $this->_normalizeFields($model, $settings);
foreach ($fields as $flag => $date) {
if ($model->hasField($flag)) {
if ($date && !$model->hasField($date)) {
trigger_error($error . $date, E_USER_NOTICE);
return;
}
continue;
}
trigger_error($error . $flag, E_USER_NOTICE);
return;
}
$this->settings[$model->alias] = $fields;
$this->softDelete($model, true);
}
/**
* Before find callback
*
* @param Model $model
* @param array $query
* @return array
*/
public function beforeFind(Model $model, $query) {
$runtime = $this->runtime[$model->alias];
if ($runtime) {
if (!is_array($query['conditions'])) {
$query['conditions'] = array();
}
$conditions = array_filter(array_keys($query['conditions']));
$fields = $this->_normalizeFields($model);
foreach ($fields as $flag => $date) {
if (true === $runtime || $flag === $runtime) {
if (!in_array($flag, $conditions) && !in_array($model->name . '.' . $flag, $conditions)) {
$query['conditions'][$model->alias . '.' . $flag] = false;
}
if ($flag === $runtime) {
break;
}
}
}
return $query;
}
}
/**
* Check if a record exists for the given id
*
* @param Model $model
* @param $id
* @return mixed
*/
public function existsAndNotDeleted(Model $model, $id) {
if ($id === null) {
$id = $model->getID();
}
if ($id === false) {
return false;
}
$exists = $model->find('count', array(
'contain' => array(),
'recursive' => -1,
'conditions' => array(
$model->alias . '.' . $model->primaryKey => $id
)
));
return ($exists ? true : false);
}
/**
* Before delete callback
*
* @param Model $model
* @param bool $cascade
* @return bool
*/
public function beforeDelete(Model $model, $cascade = true) {
$runtime = $this->runtime[$model->alias];
if ($runtime) {
if ($model->beforeDelete($cascade)) {
$this->delete($model, $model->id);
}
return false;
}
return true;
}
/**
* Mark record as deleted
*
* @param object $model
* @param int $id
* @return bool
*/
public function delete($model, $id) {
$runtime = $this->runtime[$model->alias];
$data = array();
$fields = $this->_normalizeFields($model);
foreach ($fields as $flag => $date) {
if (true === $runtime || $flag === $runtime) {
$data[$flag] = true;
if ($date) {
$data[$date] = date('Y-m-d H:i:s');
}
if ($flag === $runtime) {
break;
}
}
}
$record = $model->find('first', array(
'fields' => $model->primaryKey,
'conditions' => array($model->primaryKey => $id),
'contain' => array(),
'recursive' => -1
));
if (!empty($record)) {
$model->set($model->primaryKey, $id);
unset($model->data[$model->alias]['modified']);
unset($model->data[$model->alias]['updated']);
$result = $model->save(
array($model->alias => $data),
array('validate' => false, 'fieldList' => array_keys($data), 'atomic' => $this->_atomic, 'callbacks' => false)
);
if (!$result) {
return false;
}
$model->getEventManager()->dispatch(new CakeEvent('Model.afterDelete', $model));
}
return true;
}
/**
* Mark record as not deleted
*
* @param object $model
* @param int $id
* @return bool
*/
public function undelete($model, $id) {
$runtime = $this->runtime[$model->alias];
$this->softDelete($model, false);
$data = array();
$fields = $this->_normalizeFields($model);
foreach ($fields as $flag => $date) {
if (true === $runtime || $flag === $runtime) {
$data[$flag] = false;
if ($date) {
$data[$date] = null;
}
if ($flag === $runtime) {
break;
}
}
}
$model->create();
$model->set($model->primaryKey, $id);
$result = $model->save(
array($model->alias => $data),
array('validate' => false, 'fieldList' => array_keys($data), 'atomic' => $this->_atomic)
);
$this->softDelete($model, $runtime);
if ($result) {
return true;
}
return false;
}
/**
* Enable/disable SoftDelete functionality
*
* Usage from model:
* $this->softDelete(false); deactivate this behavior for model
* $this->softDelete('field_two'); enabled only for this flag field
* $this->softDelete(true); enable again for all flag fields
* $config = $this->softDelete(null); for obtaining current setting
*
* @param object $model
* @param mixed $active
* @return mixed if $active is null, then current setting/null, or boolean if runtime setting for model was changed
*/
public function softDelete($model, $active) {
if (is_null($active)) {
return isset($this->runtime[$model->alias]) ? $this->runtime[$model->alias] : null;
}
$result = !isset($this->runtime[$model->alias]) || $this->runtime[$model->alias] !== $active;
$this->runtime[$model->alias] = $active;
$this->_softDeleteAssociations($model, $active);
return $result;
}
/**
* Returns number of outdated softdeleted records prepared for purge
*
* @param object $model
* @param mixed $expiration anything parseable by strtotime(), by default '-90 days'
* @return int
*/
public function purgeDeletedCount($model, $expiration = '-90 days') {
$runtime = $this->runtime[$model->alias];
$this->softDelete($model, false);
$result = $model->find('count', array(
'conditions' => $this->_purgeDeletedConditions($model, $expiration),
'recursive' => -1,
'contain' => array()
)
);
$this->runtime[$model->alias] = $runtime;
return $result;
}
/**
* Purge table
*
* @param object $model
* @param mixed $expiration anything parseable by strtotime(), by default '-90 days'
* @return bool if there were some outdated records
*/
public function purgeDeleted($model, $expiration = '-90 days') {
$this->softDelete($model, false);
$records = $model->find('all', array(
'conditions' => $this->_purgeDeletedConditions($model, $expiration),
'fields' => array($model->primaryKey),
'recursive' => -1
));
if ($records) {
foreach ($records as $record) {
$model->delete($record[$model->alias][$model->primaryKey]);
}
return true;
}
return false;
}
/**
* Returns conditions for finding outdated records
*
* @param object $model
* @param mixed $expiration anything parseable by strtotime(), by default '-90 days'
* @return array
*/
protected function _purgeDeletedConditions($model, $expiration = '-90 days') {
$purgeDate = date('Y-m-d H:i:s', strtotime($expiration));
$conditions = array();
foreach ($this->settings[$model->alias] as $flag => $date) {
$conditions[$model->alias . '.' . $flag] = true;
if ($date) {
$conditions[$model->alias . '.' . $date . ' <'] = $purgeDate;
}
}
return $conditions;
}
/**
* Return normalized field array
*
* @param object $model
* @param array $settings
* @return array
*/
protected function _normalizeFields($model, $settings = array()) {
if (empty($settings)) {
$settings = $this->settings[$model->alias];
}
$result = array();
foreach ($settings as $flag => $date) {
if (is_numeric($flag)) {
$flag = $date;
$date = false;
}
$result[$flag] = $date;
}
return $result;
}
/**
* Modifies conditions of hasOne and hasMany associations
*
* If multiple delete flags are configured for model, then $active = true doesn't
* do anything - you have to alter conditions in association definition
*
* @param Model $model
* @param mixed $active
* @return void
*/
protected function _softDeleteAssociations(Model $model, $active) {
if (empty($model->belongsTo)) {
return;
}
$fields = array_keys($this->_normalizeFields($model));
$parentModels = array_keys($model->belongsTo);
foreach ($parentModels as $parentModel) {
list($plugin, $modelClass) = pluginSplit($parentModel, true);
App::uses($modelClass, $plugin . 'Model');
if (!class_exists($modelClass)) {
throw new MissingModelException(array('class' => $modelClass));
}
$model->{$parentModel} = new $parentModel(null, null, $model->useDbConfig);
foreach (array('hasOne', 'hasMany') as $assocType) {
if (empty($model->{$parentModel}->{$assocType})) {
continue;
}
foreach ($model->{$parentModel}->{$assocType} as $assoc => $assocConfig) {
$modelName = empty($assocConfig['className']) ? $assoc : @$assocConfig['className'];
if ((!empty($model->plugin) && strstr($model->plugin . '.', $model->alias) === false ? $model->plugin . '.' : '') . $model->alias !== $modelName) {
continue;
}
$conditions =& $model->{$parentModel}->{$assocType}[$assoc]['conditions'];
if (!is_array($conditions)) {
$model->{$parentModel}->{$assocType}[$assoc]['conditions'] = array();
}
$multiFields = 1 < count($fields);
foreach ($fields as $field) {
if ($active) {
if (!isset($conditions[$field]) && !isset($conditions[$assoc . '.' . $field])) {
if (is_string($active)) {
if ($field == $active) {
$conditions[$assoc . '.' . $field] = false;
} elseif (isset($conditions[$assoc . '.' . $field])) {
unset($conditions[$assoc . '.' . $field]);
}
} elseif (!$multiFields) {
$conditions[$assoc . '.' . $field] = false;
}
}
} elseif (isset($conditions[$assoc . '.' . $field])) {
unset($conditions[$assoc . '.' . $field]);
}
}
}
}
}
}
/**
* Soft delete all
*
* @param Model $model
* @param array $conditions
* @return void
*/
public function softDeleteAll(Model $model, $conditions = array()) {
$results = $model->find('all', array(
'contain' => array(),
'recursive' => -1,
'conditions' => $conditions,
'fields' => array(
$model->alias . '.' . $model->primaryKey
)
));
if (empty($results)) {
return;
}
foreach ($results as $result) {
$this->delete($model, $result[$model->alias][$model->primaryKey]);
}
}
}