FileWatcher.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace think\swoole;
  3. use Swoole\Timer;
  4. use Symfony\Component\Finder\Finder;
  5. use Symfony\Component\Finder\SplFileInfo;
  6. class FileWatcher
  7. {
  8. protected $finder;
  9. protected $files = [];
  10. public function __construct($directory, $exclude, $name)
  11. {
  12. $this->finder = new Finder();
  13. $this->finder
  14. ->files()
  15. ->name($name)
  16. ->in(array_filter((array) $directory, function ($dir) {
  17. return is_dir($dir);
  18. }))
  19. ->exclude($exclude);
  20. }
  21. protected function findFiles()
  22. {
  23. $files = [];
  24. /** @var SplFileInfo $f */
  25. foreach ($this->finder as $f) {
  26. $files[$f->getRealpath()] = $f->getMTime();
  27. }
  28. return $files;
  29. }
  30. public function watch(callable $callback)
  31. {
  32. $this->files = $this->findFiles();
  33. Timer::tick(1000, function () use ($callback) {
  34. $files = $this->findFiles();
  35. foreach ($files as $path => $time) {
  36. if (empty($this->files[$path]) || $this->files[$path] != $time) {
  37. call_user_func($callback);
  38. break;
  39. }
  40. }
  41. $this->files = $files;
  42. });
  43. }
  44. }