September 21, 2010

Safe RecursiveDirectoryIterator

I love SPL... so simple, so powerful, so flexible.

RecursiveDirectoryIterator was having problems while scanning a directory and threw me some nice errors on permissions, so I coded the snippet below...

class SafeRecursiveDirectoryIterator extends RecursiveFilterIterator
{
    public function __construct(RecursiveDirectoryIterator $iterator)
    {
        parent::__construct($iterator);
    }

    public function accept()
    {
        $it       = $this->getInnerIterator();
        $dot      = $it->isDot();
        $readable = $it->isReadable();
        $hidden   = substr($it->getFilename(), 0, 1) === '.';
        return !$dot && $readable && !$hidden;
    }
}