DataRecycleLog.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. * @param array|null $ids
  27. * @throws Throwable
  28. */
  29. public function restore(array $ids = null): void
  30. {
  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. * @param string|int|null $id
  59. * @throws Throwable
  60. */
  61. public function info(string|int $id = null): void
  62. {
  63. $row = $this->model
  64. ->withJoin($this->withJoinTable, $this->withJoinType)
  65. ->where('data_recycle_log.id', $id)
  66. ->find();
  67. if (!$row) {
  68. $this->error(__('Record not found'));
  69. }
  70. $data = $this->jsonToArray($row['data']);
  71. if (is_array($data)) {
  72. foreach ($data as $key => $item) {
  73. $data[$key] = $this->jsonToArray($item);
  74. }
  75. }
  76. $row['data'] = $data;
  77. $this->success('', [
  78. 'row' => $row
  79. ]);
  80. }
  81. protected function jsonToArray($value = '')
  82. {
  83. if (!is_string($value)) {
  84. return $value;
  85. }
  86. $data = json_decode($value, true);
  87. if (($data && is_object($data)) || (is_array($data) && !empty($data))) {
  88. return $data;
  89. }
  90. return $value;
  91. }
  92. }