Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over multiple RecursiveDirectoryIterator

Tags:

iterator

php

I currently have the following PHP:

$directoryIterator = new RecursiveDirectoryIterator( __DIR__ . '/tests/phpunit/' );

/**
 * @var SplFileInfo $fileInfo
 */
foreach ( new RecursiveIteratorIterator( $directoryIterator ) as $fileInfo ) {
    if ( substr( $fileInfo->getFilename(), -8 ) === 'Test.php' ) {
        $files[] = $fileInfo->getPathname();
    }
}

This creates an array with the paths to the files ending with Test.php in /tests/phpunit. Works nice and well. However now I also want to register stuff in /tests/integration. (There are more things in /tests, so I cannot simply go through that whole directory.) I could copy the code, but that’s be lame. So now I'm trying to figure out how to loop over two RecursiveDirectoryIterator instances. Is this possible in a sane way?

like image 401
Jeroen De Dauw Avatar asked Jun 13 '13 05:06

Jeroen De Dauw


1 Answers

To iterate over iterators you can use AppendIterator class.

$directoryIterator = new RecursiveDirectoryIterator( __DIR__ . '/tests/phpunit/' );
$directoryIterator1 = new RecursiveDirectoryIterator( __DIR__ . '/tests/integration/' );
$iterator = new AppendIterator();
$iterator->append(new RecursiveIteratorIterator( $directoryIterator ));
$iterator->append(new RecursiveIteratorIterator( $directoryIterator1 ));

/**
 * @var SplFileInfo $fileInfo
 */
foreach ($iterator as $fileInfo) {
    if ( substr( $fileInfo->getFilename(), -8 ) === 'Test.php' ) {
        $files[] = $fileInfo->getPathname();
    }
}
like image 71
sectus Avatar answered Nov 17 '22 08:11

sectus