mardi 6 juillet 2021

Decorate an Iterator in PHP - enable skipping

I have a class that is basically a decorator for PHP's DirectoryIterator. Each file's contents are processed by the class and then returned by the current() method. Currently, when the file is a dot file or the file cannot be processed, I return false from the current() method. But I would rather like to skip the dot- and unprocessable files, and only return processed data.

P.S. The code below is a simplified example. I don't want to pre-process all files in the constructor.

class Pages implements \Iterator
{
    public function __construct(string $path)
    {
        $this->di = new \DirectoryIterator($path);
    }

    public function rewind() {
        return $this->di->rewind();
    }

    public function current() {
        $file = $this->di->current();
        if($file->isDot()) {
            return false;
        }
        $content = file_get_contents($file->getPathName());
        if($content === 'Cannot be processed!') {
            return false;
        }
        return $content;
    }

    public function key() {
        return $this->di->key();
    }

    public function next() {
        return $this->di->next();
    }

    public function valid() {
        return $this->di->valid();
    }
}

Aucun commentaire:

Enregistrer un commentaire