John Davidson

design patterns - Decorate an Iterator in PHP - enable skipping

0 comments
Message:


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


My Answer:
To enable skipping dot- and unprocessable files in the iterator, you can modify the current() method to skip these files and only return processed data. Here's an updated version of the Pages class with this functionality:

php
class Pages implements \Iterator
{
private $di;
private $currentContent;

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

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

public function current() {
return $this->currentContent;
}

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

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

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

private function fetchNextValidFile() {
while ($this->di->valid()) {
$file = $this->di->current();
$this->di->next();

if ($file->isDot()) {
continue;
}

$content = file_get_contents($file->getPathname());
if ($content === 'Cannot be processed!') {
continue;
}

$this->currentContent = $content;
return;
}

$this->currentContent = false;
}
}


In this updated version, the `fetchNextValidFile()` method is introduced to handle skipping dot- and unprocessable files. It iterates through the DirectoryIterator until it finds a valid file with processed content, which is then stored in the `$currentContent` property. The `current()` method now simply returns the stored content.

You can use this updated Pages class to iterate through files while skipping dot files and files that cannot be processed.

Rate this post

5 of 5 based on 5284 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us