Skip to content

Instantly share code, notes, and snippets.

@assertchris
Last active August 30, 2015 15:25
Show Gist options
  • Save assertchris/3bd36713c0a4753ff96b to your computer and use it in GitHub Desktop.
Save assertchris/3bd36713c0a4753ff96b to your computer and use it in GitHub Desktop.
<?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;
}
@dannykopping
Copy link

Had to do exactly this yesterday, but I'm working with Symfony's Finder

$finder = new Finder();
$files  = $finder->in($this->basePath)->name('/\.js$/');

@tomphp
Copy link

tomphp commented Aug 13, 2014

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);
}

@assertchris
Copy link
Author

Lovely.

@stof
Copy link

stof commented Aug 13, 2014

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