Last active
August 30, 2015 15:25
-
-
Save assertchris/3bd36713c0a4753ff96b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @param $path | |
* @param $extension | |
* | |
* @return array | |
*/ | |
function getFilesInPathWithExtension($path, $extension) | |
{ | |
$directoryIterator = new RecursiveDirectoryIterator($path); | |
$recursiveIterator = new RecursiveIteratorIterator($directoryIterator); | |
$files = []; | |
foreach ($recursiveIterator as $item) { | |
if ($item->isFile() and $item->getExtension() === $extension) { | |
$files[] = $item; | |
} | |
if ($item->isDir() and $item->getFilename() !== "." and $item->getFilename() !== "..") { | |
$files = array_merge( | |
$files, getFilesInPathWithExtension($item->getPathName(), $extension) | |
); | |
} | |
} | |
return $files; | |
} |
Neater SPL version ;-)
<?php
/**
* @param $path
* @param $extension
*
* @return array
*/
function getFilesInPathWithExtension($path, $extension)
{
$directoryIterator = new RecursiveDirectoryIterator($path);
$recursiveIterator = new RecursiveIteratorIterator($directoryIterator);
$extensionFilterIterator = new CallbackFilterIterator($recursiveIterator, function ($item) use ($extension) {
return $item->isFile() && $item->getExtension() === $extension;
});
return iterator_to_array($extensionFilterIterator);
}
Lovely.
note that the Symfony Finder component is actually just a builder for the SPL-based code (its IteratorAggregate implementation will build the SPL iterator stack corresponding to the conditions added in the finder)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Had to do exactly this yesterday, but I'm working with Symfony's
Finder