SoftDeleteBehavior.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. <?php
  2. namespace common\behaviors;
  3. use yii\base\Behavior;
  4. use yii\base\InvalidConfigException;
  5. use yii\base\ModelEvent;
  6. use yii\db\BaseActiveRecord;
  7. /**
  8. * SoftDeleteBehavior provides support for "soft" delete of ActiveRecord models as well as restoring them
  9. * from "deleted" state.
  10. *
  11. * ```php
  12. * class Item extends ActiveRecord
  13. * {
  14. * public function behaviors()
  15. * {
  16. * return [
  17. * 'softDeleteBehavior' => [
  18. * 'class' => SoftDeleteBehavior::className(),
  19. * 'softDeleteAttributeValues' => [
  20. * 'isDeleted' => true
  21. * ],
  22. * ],
  23. * ];
  24. * }
  25. * }
  26. * ```
  27. *
  28. * @property BaseActiveRecord $owner owner ActiveRecord instance.
  29. * @property boolean $replaceRegularDelete whether to perform soft delete instead of regular delete.
  30. * If enabled [[BaseActiveRecord::delete()]] will perform soft deletion instead of actual record deleting.
  31. *
  32. * @author Paul Klimov <klimov.paul@gmail.com>
  33. * @since 1.0
  34. */
  35. class SoftDeleteBehavior extends Behavior
  36. {
  37. /**
  38. * @event ModelEvent an event that is triggered before deleting a record.
  39. * You may set [[ModelEvent::isValid]] to be false to stop the deletion.
  40. */
  41. const EVENT_BEFORE_SOFT_DELETE = 'beforeSoftDelete';
  42. /**
  43. * @event Event an event that is triggered after a record is deleted.
  44. */
  45. const EVENT_AFTER_SOFT_DELETE = 'afterSoftDelete';
  46. /**
  47. * @event ModelEvent an event that is triggered before record is restored from "deleted" state.
  48. * You may set [[ModelEvent::isValid]] to be false to stop the restoration.
  49. */
  50. const EVENT_BEFORE_RESTORE = 'beforeRestore';
  51. /**
  52. * @event Event an event that is triggered after a record is restored from "deleted" state.
  53. */
  54. const EVENT_AFTER_RESTORE = 'afterRestore';
  55. /**
  56. * @var array values of the owner attributes, which should be applied on soft delete, in format: [attributeName => attributeValue].
  57. * Those may raise a flag:
  58. *
  59. * ```php
  60. * ['isDeleted' => true]
  61. * ```
  62. *
  63. * or switch status:
  64. *
  65. * ```php
  66. * ['statusId' => Item::STATUS_DELETED]
  67. * ```
  68. *
  69. * Attribute value can be a callable:
  70. *
  71. * ```php
  72. * ['isDeleted' => function ($model) {return time()}]
  73. * ```
  74. */
  75. public $softDeleteAttributeValues = [
  76. 'isDeleted' => true
  77. ];
  78. /**
  79. * @var array|null values of the owner attributes, which should be applied on restoration from "deleted" state,
  80. * in format: [attributeName => attributeValue]. If not set value will be automatically detected from [[softDeleteAttributeValues]].
  81. */
  82. public $restoreAttributeValues;
  83. /**
  84. * @var boolean whether to invoke owner [[BaseActiveRecord::beforeDelete()]] and [[BaseActiveRecord::afterDelete()]]
  85. * while performing soft delete. This option affects only [[softDelete()]] method.
  86. */
  87. public $invokeDeleteEvents = true;
  88. /**
  89. * @var callable|null callback, which execution determines if record should be "hard" deleted instead of being marked
  90. * as deleted. Callback should match following signature: `boolean function(BaseActiveRecord $model)`
  91. * For example:
  92. *
  93. * ```php
  94. * function ($user) {
  95. * return $user->lastLoginDate === null;
  96. * }
  97. * ```
  98. */
  99. public $allowDeleteCallback;
  100. /**
  101. * @var string class name of the exception, which should trigger a fallback to [[softDelete()]] method from [[safeDelete()]].
  102. * By default [[\yii\db\IntegrityException]] is used, which means soft deleting will be performed on foreign constraint
  103. * violation DB exception.
  104. * You may specify another exception class here to customize fallback error level. For example: usage of [[\Exception]]
  105. * will cause soft-delete fallback on any error during regular deleting.
  106. * @see safeDelete()
  107. */
  108. public $deleteFallbackException = 'yii\db\IntegrityException';
  109. /**
  110. * @var boolean whether to perform soft delete instead of regular delete.
  111. * If enabled [[BaseActiveRecord::delete()]] will perform soft deletion instead of actual record deleting.
  112. */
  113. private $_replaceRegularDelete = false;
  114. /**
  115. * @return boolean
  116. */
  117. public function getReplaceRegularDelete()
  118. {
  119. return $this->_replaceRegularDelete;
  120. }
  121. /**
  122. * @param boolean $replaceRegularDelete
  123. */
  124. public function setReplaceRegularDelete($replaceRegularDelete)
  125. {
  126. $this->_replaceRegularDelete = $replaceRegularDelete;
  127. if (is_object($this->owner)) {
  128. $owner = $this->owner;
  129. $this->detach();
  130. $this->attach($owner);
  131. }
  132. }
  133. /**
  134. * Marks the owner as deleted.
  135. * @return integer|false the number of rows marked as deleted, or false if the soft deletion is unsuccessful for some reason.
  136. * Note that it is possible the number of rows deleted is 0, even though the soft deletion execution is successful.
  137. */
  138. public function softDelete()
  139. {
  140. if ($this->isDeleteAllowed()) {
  141. return $this->owner->delete();
  142. }
  143. if ($this->invokeDeleteEvents && !$this->owner->beforeDelete()) {
  144. return false;
  145. }
  146. $result = $this->softDeleteInternal();
  147. if ($this->invokeDeleteEvents) {
  148. $this->owner->afterDelete();
  149. }
  150. return $result;
  151. }
  152. /**
  153. * Marks the owner as deleted.
  154. * @return integer|false the number of rows marked as deleted, or false if the soft deletion is unsuccessful for some reason.
  155. */
  156. protected function softDeleteInternal()
  157. {
  158. $result = false;
  159. if ($this->beforeSoftDelete()) {
  160. $attributes = [];
  161. foreach ($this->softDeleteAttributeValues as $attribute => $value) {
  162. if (!is_scalar($value) && is_callable($value)) {
  163. $value = call_user_func($value, $this->owner);
  164. }
  165. $attributes[$attribute] = $value;
  166. }
  167. $result = $this->owner->updateAttributes($attributes);
  168. $this->afterSoftDelete();
  169. }
  170. return $result;
  171. }
  172. /**
  173. * This method is invoked before soft deleting a record.
  174. * The default implementation raises the [[EVENT_BEFORE_SOFT_DELETE]] event.
  175. * @return boolean whether the record should be deleted. Defaults to true.
  176. */
  177. public function beforeSoftDelete()
  178. {
  179. if (method_exists($this->owner, 'beforeSoftDelete')) {
  180. if (!$this->owner->beforeSoftDelete()) {
  181. return false;
  182. }
  183. }
  184. $event = new ModelEvent();
  185. $this->owner->trigger(self::EVENT_BEFORE_SOFT_DELETE, $event);
  186. return $event->isValid;
  187. }
  188. /**
  189. * This method is invoked after soft deleting a record.
  190. * The default implementation raises the [[EVENT_AFTER_SOFT_DELETE]] event.
  191. * You may override this method to do postprocessing after the record is deleted.
  192. * Make sure you call the parent implementation so that the event is raised properly.
  193. */
  194. public function afterSoftDelete()
  195. {
  196. if (method_exists($this->owner, 'afterSoftDelete')) {
  197. $this->owner->afterSoftDelete();
  198. }
  199. $this->owner->trigger(self::EVENT_AFTER_SOFT_DELETE);
  200. }
  201. /**
  202. * @return boolean whether owner "hard" deletion allowed or not.
  203. */
  204. protected function isDeleteAllowed()
  205. {
  206. if ($this->allowDeleteCallback === null) {
  207. return false;
  208. }
  209. return call_user_func($this->allowDeleteCallback, $this->owner);
  210. }
  211. // Restore :
  212. /**
  213. * Restores record from "deleted" state, after it has been "soft" deleted.
  214. * @return integer|false the number of restored rows, or false if the restoration is unsuccessful for some reason.
  215. */
  216. public function restore()
  217. {
  218. $result = false;
  219. if ($this->beforeRestore()) {
  220. $result = $this->restoreInternal();
  221. $this->afterRestore();
  222. }
  223. return $result;
  224. }
  225. /**
  226. * @return integer the number of restored rows.
  227. * @throws InvalidConfigException on invalid configuration.
  228. */
  229. protected function restoreInternal()
  230. {
  231. $restoreAttributeValues = $this->restoreAttributeValues;
  232. if ($restoreAttributeValues === null) {
  233. foreach ($this->softDeleteAttributeValues as $name => $value) {
  234. if (is_bool($value) || $value === 1 || $value === 0) {
  235. $restoreValue = !$value;
  236. } elseif (is_int($value)) {
  237. if ($value === 1) {
  238. $restoreValue = 0;
  239. } elseif ($value === 0) {
  240. $restoreValue = 1;
  241. } else {
  242. $restoreValue = $value + 1;
  243. }
  244. } else {
  245. throw new InvalidConfigException('Unable to automatically determine restore attribute values, "' . get_class($this) . '::restoreAttributeValues" should be explicitly set.');
  246. }
  247. $restoreAttributeValues[$name] = $restoreValue;
  248. }
  249. }
  250. $attributes = [];
  251. foreach ($restoreAttributeValues as $attribute => $value) {
  252. if (!is_scalar($value) && is_callable($value)) {
  253. $value = call_user_func($value, $this->owner);
  254. }
  255. $attributes[$attribute] = $value;
  256. }
  257. return $this->owner->updateAttributes($attributes);
  258. }
  259. /**
  260. * This method is invoked before record is restored from "deleted" state.
  261. * The default implementation raises the [[EVENT_BEFORE_RESTORE]] event.
  262. * @return boolean whether the record should be restored. Defaults to true.
  263. */
  264. public function beforeRestore()
  265. {
  266. if (method_exists($this->owner, 'beforeRestore')) {
  267. if (!$this->owner->beforeRestore()) {
  268. return false;
  269. }
  270. }
  271. $event = new ModelEvent();
  272. $this->owner->trigger(self::EVENT_BEFORE_RESTORE, $event);
  273. return $event->isValid;
  274. }
  275. /**
  276. * This method is invoked after record is restored from "deleted" state.
  277. * The default implementation raises the [[EVENT_AFTER_RESTORE]] event.
  278. * You may override this method to do postprocessing after the record is restored.
  279. * Make sure you call the parent implementation so that the event is raised properly.
  280. */
  281. public function afterRestore()
  282. {
  283. if (method_exists($this->owner, 'afterRestore')) {
  284. $this->owner->afterRestore();
  285. }
  286. $this->owner->trigger(self::EVENT_AFTER_RESTORE);
  287. }
  288. /**
  289. * Attempts to perform regular [[BaseActiveRecord::delete()]], if it fails with exception, falls back to [[softDelete()]].
  290. * If owner database supports transactions, regular deleting attempt will be enclosed in transaction with rollback
  291. * in case of failure.
  292. * @return false|integer number of affected rows.
  293. * @throws \Exception on failure.
  294. */
  295. public function safeDelete()
  296. {
  297. try {
  298. $transaction = $this->beginTransaction();
  299. $result = $this->owner->delete();
  300. if (isset($transaction)) {
  301. $transaction->commit();
  302. }
  303. } catch (\Exception $exception) {
  304. if (isset($transaction)) {
  305. $transaction->rollback();
  306. }
  307. $fallbackExceptionClass = $this->deleteFallbackException;
  308. if ($exception instanceof $fallbackExceptionClass) {
  309. $result = $this->softDeleteInternal();
  310. } else {
  311. throw $exception;
  312. }
  313. }
  314. return $result;
  315. }
  316. /**
  317. * Begins new database transaction if owner allows it.
  318. * @return \yii\db\Transaction|null transaction instance or `null` if not available.
  319. */
  320. private function beginTransaction()
  321. {
  322. $db = $this->owner->getDb();
  323. if ($db->hasMethod('beginTransaction')) {
  324. return $db->beginTransaction();
  325. }
  326. return null;
  327. }
  328. // Events :
  329. /**
  330. * @inheritdoc
  331. */
  332. public function events()
  333. {
  334. if ($this->getReplaceRegularDelete()) {
  335. return [
  336. BaseActiveRecord::EVENT_BEFORE_DELETE => 'beforeDelete',
  337. ];
  338. } else {
  339. return [];
  340. }
  341. }
  342. /**
  343. * Handles owner 'beforeDelete' owner event, applying soft delete and preventing actual deleting.
  344. * @param ModelEvent $event event instance.
  345. */
  346. public function beforeDelete($event)
  347. {
  348. if (!$this->isDeleteAllowed()) {
  349. $this->softDeleteInternal();
  350. $event->isValid = false;
  351. }
  352. }
  353. }