Skip to content

Instantly share code, notes, and snippets.

@hakre
Created April 20, 2014 11:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hakre/11111534 to your computer and use it in GitHub Desktop.
Save hakre/11111534 to your computer and use it in GitHub Desktop.
Filter recursive directory traversal and file listing in PHP with RecursiveDirectoryIterator
<?php
/**
* Class HiddenFilesAndFolderFilterIterator
*
* Under *Nix hidden files and directories start with a dot ("."). This RFI does not traverse
* hidden directories and filters hidden files from RecursiveDirectoryIterator listing.
*/
class HiddenFilesAndFolderFilterIterator extends RecursiveFilterIterator
{
/**
* This RecursiveFilterIterator works only with the more concrete RecursiveDirectoryIterator type.
*
* @param RecursiveDirectoryIterator $iterator
*/
public function __construct(RecursiveDirectoryIterator $iterator)
{
parent::__construct($iterator);
}
/**
* Check whether the current element of the iterator is acceptable
*
* @link http://php.net/manual/en/filteriterator.accept.php
* @return bool true if the current element is acceptable, otherwise false.
*/
public function accept()
{
/** @var RecursiveDirectoryIterator $this PHP SPL RFI/RII does decorate */
$current = $this->getBasename();
return strlen($current) && $current[0] !== ".";
}
/**
* By default, PHP does not filter hasChildren(), so this needs to be added.
*
* @return bool
*/
public function hasChildren()
{
return parent::hasChildren() && $this->accept();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment