Clear.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\app\command;
  12. use think\console\Command;
  13. use think\console\Input;
  14. use think\console\input\Argument;
  15. use think\console\input\Option;
  16. use think\console\Output;
  17. class Clear extends Command
  18. {
  19. protected function configure()
  20. {
  21. // 指令配置
  22. $this->setName('clear')
  23. ->addArgument('app', Argument::OPTIONAL, 'app name .')
  24. ->addOption('cache', 'c', Option::VALUE_NONE, 'clear cache file')
  25. ->addOption('log', 'l', Option::VALUE_NONE, 'clear log file')
  26. ->addOption('dir', 'r', Option::VALUE_NONE, 'clear empty dir')
  27. ->setDescription('Clear runtime file');
  28. }
  29. protected function execute(Input $input, Output $output)
  30. {
  31. $app = $input->getArgument('app') ?: '';
  32. $runtimePath = $this->app->getRootPath() . 'runtime' . DIRECTORY_SEPARATOR . ($app ? $app . DIRECTORY_SEPARATOR : '');
  33. if ($input->getOption('cache')) {
  34. $path = $runtimePath . 'cache';
  35. } elseif ($input->getOption('log')) {
  36. $path = $runtimePath . 'log';
  37. } else {
  38. $path = $runtimePath;
  39. }
  40. $rmdir = $input->getOption('dir') ? true : false;
  41. $this->clear(rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR, $rmdir);
  42. $output->writeln("<info>Clear Successed</info>");
  43. }
  44. protected function clear(string $path, bool $rmdir): void
  45. {
  46. $files = is_dir($path) ? scandir($path) : [];
  47. foreach ($files as $file) {
  48. if ('.' != $file && '..' != $file && is_dir($path . $file)) {
  49. array_map('unlink', glob($path . $file . DIRECTORY_SEPARATOR . '*.*'));
  50. if ($rmdir) {
  51. rmdir($path . $file);
  52. }
  53. } elseif ('.gitignore' != $file && is_file($path . $file)) {
  54. unlink($path . $file);
  55. }
  56. }
  57. }
  58. }