class-filesystemvisitor.php
92 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WordPress\Filesystem\Visitor; |
| 4 | |
| 5 | use ArrayIterator; |
| 6 | use WordPress\Filesystem\Filesystem; |
| 7 | |
| 8 | use function WordPress\Filesystem\wp_join_unix_paths; |
| 9 | |
| 10 | class FilesystemVisitor { |
| 11 | private $filesystem; |
| 12 | private $directories = array(); |
| 13 | private $files = array(); |
| 14 | private $current_event; |
| 15 | private $iterator_stack = array(); |
| 16 | private $current_iterator; |
| 17 | private $depth = - 1; |
| 18 | |
| 19 | public function __construct( Filesystem $filesystem ) { |
| 20 | $this->filesystem = $filesystem; |
| 21 | $this->iterator_stack[] = $this->create_iterator(); |
| 22 | } |
| 23 | |
| 24 | public function get_current_depth() { |
| 25 | return $this->depth; |
| 26 | } |
| 27 | |
| 28 | public function next() { |
| 29 | while ( ! empty( $this->iterator_stack ) ) { |
| 30 | $this->current_iterator = end( $this->iterator_stack ); |
| 31 | |
| 32 | if ( ! $this->current_iterator->valid() ) { |
| 33 | array_pop( $this->iterator_stack ); |
| 34 | continue; |
| 35 | } |
| 36 | $current = $this->current_iterator->current(); |
| 37 | $this->current_iterator->next(); |
| 38 | |
| 39 | if ( ! ( $current instanceof FileVisitorEvent ) ) { |
| 40 | // It's a directory path, push a new iterator onto the stack. |
| 41 | $this->iterator_stack[] = $this->create_iterator( $current ); |
| 42 | continue; |
| 43 | } |
| 44 | |
| 45 | if ( $current->is_entering() ) { |
| 46 | ++$this->depth; |
| 47 | } |
| 48 | $this->current_event = $current; |
| 49 | if ( $current->is_exiting() ) { |
| 50 | --$this->depth; |
| 51 | } |
| 52 | |
| 53 | return true; |
| 54 | } |
| 55 | |
| 56 | return false; |
| 57 | } |
| 58 | |
| 59 | public function get_event(): ?FileVisitorEvent { |
| 60 | return $this->current_event; |
| 61 | } |
| 62 | |
| 63 | private function create_iterator( $dir = '/' ) { |
| 64 | $this->directories = array(); |
| 65 | $this->files = array(); |
| 66 | |
| 67 | $filesystem = $this->filesystem; |
| 68 | $children = $filesystem->ls( $dir ); |
| 69 | if ( false === $children ) { |
| 70 | return new ArrayIterator( array() ); |
| 71 | } |
| 72 | |
| 73 | foreach ( $children as $child ) { |
| 74 | if ( $filesystem->is_dir( wp_join_unix_paths( $dir, $child ) ) ) { |
| 75 | $this->directories[] = $child; |
| 76 | continue; |
| 77 | } |
| 78 | $this->files[] = $child; |
| 79 | } |
| 80 | |
| 81 | $events = array(); |
| 82 | $events[] = new FileVisitorEvent( FileVisitorEvent::EVENT_ENTER, $dir, $this->files ); |
| 83 | $prefix = '/' === $dir ? '' : $dir; |
| 84 | foreach ( $this->directories as $directory ) { |
| 85 | $events[] = $prefix . '/' . $directory; // Placeholder for recursion. |
| 86 | } |
| 87 | $events[] = new FileVisitorEvent( FileVisitorEvent::EVENT_EXIT, $dir ); |
| 88 | |
| 89 | return new ArrayIterator( $events ); |
| 90 | } |
| 91 | } |
| 92 |