Cache.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /**
  3. *
  4. * @copyright ©2020 点小铺
  5. * @author hanj
  6. * @link: https://dyuit.com
  7. * Created by VSCode
  8. */
  9. namespace app\admin\controller\setting;
  10. use app\admin\controller\Controller;
  11. use think\Cache as CacheDriver;
  12. /**
  13. * 清理缓存
  14. * Class Index
  15. * @package app\admin\controller
  16. */
  17. class Cache extends Controller
  18. {
  19. /**
  20. * 清理缓存
  21. * @param bool $isForce
  22. * @return mixed
  23. */
  24. public function clear($isForce = false)
  25. {
  26. if ($this->request->isAjax()) {
  27. $this->rmCache($this->postData('cache'));
  28. return $this->renderSuccess('操作成功');
  29. }
  30. return $this->fetch('clear', [
  31. 'isForce' => !!$isForce ?: config('app_debug'),
  32. ]);
  33. }
  34. /**
  35. * 删除缓存
  36. * @param $data
  37. */
  38. private function rmCache($data)
  39. {
  40. // 数据缓存
  41. if (in_array('data', $data['item'])) {
  42. // 强制模式
  43. $isForce = isset($data['isForce']) ? !!$data['isForce'] : false;
  44. // 清除缓存
  45. CacheDriver::clear($isForce ? null : 'cache');
  46. }
  47. // 临时文件
  48. if (in_array('temp', $data['item'])) {
  49. $paths = [
  50. 'temp' => WEB_PATH . 'temp/',
  51. 'runtime' => RUNTIME_PATH . 'image/'
  52. ];
  53. foreach ($paths as $path) {
  54. $this->deleteFolder($path);
  55. }
  56. }
  57. }
  58. /**
  59. * 递归删除指定目录下所有文件
  60. * @param $path
  61. * @return bool
  62. */
  63. private function deleteFolder($path)
  64. {
  65. if (!is_dir($path))
  66. return false;
  67. // 扫描一个文件夹内的所有文件夹和文件
  68. foreach (scandir($path) as $val) {
  69. // 排除目录中的.和..
  70. if (!in_array($val, ['.', '..', '.gitignore'])) {
  71. // 如果是目录则递归子目录,继续操作
  72. if (is_dir($path . $val)) {
  73. // 子目录中操作删除文件夹和文件
  74. $this->deleteFolder($path . $val . '/');
  75. // 目录清空后删除空文件夹
  76. rmdir($path . $val . '/');
  77. } else {
  78. // 如果是文件直接删除
  79. unlink($path . $val);
  80. }
  81. }
  82. }
  83. return true;
  84. }
  85. }