Search code examples
phpphpunitvfs-stream

FilesystemIterator with vfsStream


I am using (learning) vfsStream to test file system operations on a directory tree with 23,000 items in it.

Here's what I am trying to do in a PHPUnit test:

    public function testMockFS() {
        $buffer = (array) json_decode(file_get_contents(__DIR__ . '/resources/structure.json'));
        $root = vfsStream::setup('/',null,$buffer);

        $it = new FilesystemIterator($root);
        foreach ($it as $fileInfo) {
            echo $fileInfo->getFilename() . "\n";
    }

}

Note: I know this doesn't test anything. Right now, I am just trying to get the iteration working, and so I want to print the directory structure to the screen before I start writing tests.

structure.json is a dump from production that contains a complete reproduction of the filesystem (without the filecontent, which is irrelevant for what we're working on).

vfsStream::setup() appears to work fine. No errors.

How do I iterate the vfsSystem using FilesystemIterator? I feel like either 1) $root should return a directory from the vfs that FilesystemIterator can work with, or b) I should be passing "vfs::/" as the argument, but FilesystemIterator doesn't know what "vfs::" things are.

I'm sure I'm making this harder than it has to be. Thanks in advance.


Solution

  • I figured it out. You have to use vfsStream::url('/path/to/directory/you/want');

    public function testMockFS() {
        $buffer = (array) json_decode(file_get_contents(__DIR__ . '/resources/structure.json'));
        $root = vfsStream::setup('/',null,$buffer);
    
        $it = new FilesystemIterator(vfsStream::url('/'));
        foreach ($it as $fileInfo) {
            echo $fileInfo->getFilename() . "\n";
    }
    

    }