FileConsole.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\common\command;
  4. use DirectoryIterator;
  5. use SplFileInfo;
  6. // 引入框架内置类
  7. use think\console\Command;
  8. use think\console\Input;
  9. use think\console\input\Argument;
  10. use think\console\input\Option;
  11. use think\console\Output;
  12. use think\facade\Config;
  13. use think\File;
  14. use app\common\model\FileManager;
  15. class FileConsole extends Command
  16. {
  17. protected function configure()
  18. {
  19. // 指令配置
  20. $this->setName('fileconsole')
  21. ->addArgument('name', Argument::OPTIONAL, "console name")
  22. ->addOption('dir', null, Option::VALUE_REQUIRED, 'directory name')
  23. ->setDescription('the fileconsole command');
  24. }
  25. protected function execute(Input $input, Output $output)
  26. {
  27. $name = trim($input->getArgument('name'));
  28. $name = $name ?: 'thinkphp';
  29. if ($input->hasOption('dir')) {
  30. $dir = str_replace("\\", '/', app()->getRootPath() . $input->getOption('dir'));
  31. } else {
  32. $dir = str_replace("\\", '/', Config::get('filesystem.disks.public.root')) .'/';
  33. }
  34. // 指令输出
  35. $output->writeln('fileconsole :' . $name . "--dir: " . $dir);
  36. $this->$name($dir);
  37. $output->writeln('..ok');
  38. }
  39. /**
  40. * 建立文件管理目录索引(递归遍历目录)
  41. */
  42. public function scan($dir)
  43. {
  44. if (is_file($dir)) {
  45. $file = new File($dir);
  46. FileManager::saveFileInfo($file);
  47. } else {
  48. $dirs = new DirectoryIterator($dir);
  49. foreach ($dirs as $fileInfo) {
  50. if($fileInfo->isDot() || $fileInfo->getFilename() == '.gitignore') {
  51. continue;
  52. }
  53. $this->scan($dirs->getPath() . '/' . $fileInfo->getFilename());
  54. }
  55. }
  56. }
  57. /**
  58. * 清除无效目录索引
  59. */
  60. public function clear($dir = '')
  61. {
  62. $list = FileManager::select();
  63. foreach ($list as $value) {
  64. $file = app()->getRootPath() . 'public/' . $value->filepath;
  65. if (!is_file($file)) {
  66. FileManager::destroy($value->fileid);
  67. }
  68. }
  69. }
  70. }