Home

Algorithmic Advent: 19 – File extension filter iterator (PHP/SPL)

Published on 19 Dec 2010. Tagged with php, algorithmicadvent.

/**
 * Example:
 *
 * $path      = '/a/directory';
 * $whitelist = array('txt'); // List of file extensions to filter
 *
 * $iterator = new FileExtensionFilterIterator(
 *                 new RecursiveIteratorIterator(
 *                     new RecursiveDirectoryIterator($path)),
 *                 $whitelist);
 *
 * foreach ($iterator as $file) {
 *     echo $file, "<br />";
 * } * 
 */
class FileExtensionFilterIterator extends FilterIterator
{
    protected $whitelist;

    public function __construct(Iterator $iterator, array $whitelist)
    {
        parent::__construct($iterator);
        $this->whitelist = $whitelist;
    }

    public function accept()
    {
        $fileInfo = parent::current();

        // Allow only files
        if (!$fileInfo->isFile()) {
            return false;
        }

        // Only allow file extensinos from $whitelist
        $pi = pathinfo($fileInfo->getFilename());
        if (!in_array(strtolower($pi['extension']), $this->whitelist)) {
            return false;
        }

        return true;
    }
}