DataRecycleLog.php 2.7 KB

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