DataRecycleLog.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace app\admin\controller\security;
  3. use Throwable;
  4. use think\facade\Db;
  5. use app\common\controller\Backend;
  6. use app\admin\model\DataRecycleLog as DataRecycleLogModel;
  7. class DataRecycleLog extends Backend
  8. {
  9. /**
  10. * @var object
  11. * @phpstan-var DataRecycleLogModel
  12. */
  13. protected object $model;
  14. // 排除字段
  15. protected string|array $preExcludeFields = [];
  16. protected string|array $quickSearchField = 'recycle.name';
  17. protected array $withJoinTable = ['recycle', 'admin'];
  18. public function initialize(): void
  19. {
  20. parent::initialize();
  21. $this->model = new DataRecycleLogModel();
  22. }
  23. /**
  24. * 还原
  25. * @param array|null $ids
  26. * @throws Throwable
  27. */
  28. public function restore(array $ids = null): void
  29. {
  30. $data = $this->model->where('id', 'in', $ids)->select();
  31. if (!$data) {
  32. $this->error(__('Record not found'));
  33. }
  34. $count = 0;
  35. $this->model->startTrans();
  36. try {
  37. foreach ($data as $row) {
  38. $recycleData = json_decode($row['data'], true);
  39. if (is_array($recycleData) && Db::name($row->data_table)->insert($recycleData)) {
  40. $row->delete();
  41. $count++;
  42. }
  43. }
  44. $this->model->commit();
  45. } catch (Throwable $e) {
  46. $this->model->rollback();
  47. $this->error($e->getMessage());
  48. }
  49. if ($count) {
  50. $this->success();
  51. } else {
  52. $this->error(__('No rows were restore'));
  53. }
  54. }
  55. /**
  56. * 详情
  57. * @param string|int|null $id
  58. * @throws Throwable
  59. */
  60. public function info(string|int $id = null): void
  61. {
  62. $row = $this->model
  63. ->withJoin($this->withJoinTable, $this->withJoinType)
  64. ->where('data_recycle_log.id', $id)
  65. ->find();
  66. if (!$row) {
  67. $this->error(__('Record not found'));
  68. }
  69. $data = $this->jsonToArray($row['data']);
  70. if (is_array($data)) {
  71. foreach ($data as $key => $item) {
  72. $data[$key] = $this->jsonToArray($item);
  73. }
  74. }
  75. $row['data'] = $data;
  76. $this->success('', [
  77. 'row' => $row
  78. ]);
  79. }
  80. protected function jsonToArray($value = '')
  81. {
  82. if (!is_string($value)) {
  83. return $value;
  84. }
  85. $data = json_decode($value, true);
  86. if (($data && is_object($data)) || (is_array($data) && !empty($data))) {
  87. return $data;
  88. }
  89. return $value;
  90. }
  91. }