Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 11 ■ SPL FILE AND DIRECTORY HANDLING^177

class FileContentFilter extends FilterIterator {

protected $search;

public function __construct($it, $search) {
parent::__construct($it);
$this->search = $search;
}

public function accept() {
//Current holds a file name
$fo = new SplFileObject($this->current());

//Search within the file
$file = new InFileSearch($fo, $this->search);

//Accept if more than one line was found
return (count(iterator_to_array($file)) > 0);
}
}

//Create a recursive iterator for Directory Structure
$dir = new RecursiveDirectoryIterator('/path/to/php-src/ext/spl/examples/');

//Flatten the recursive iterator
$it = new RecursiveIteratorIterator($dir);

//Filter
$filter = new FileContentFilter($it, 'Kevin McArthur');

print_r(iterator_to_array($filter));

Just the Facts


This chapter introduced the SPL facilities for file I/O. These include the SplFileInfo object,
directory iterators, and the SplFileObject class.
With SplFileInfo, you can get file names, sizes, and permissions. You can also integrate
overloaded versions of this class.
Using DirectoryIterator, RecursiveDirectoryIterator, and other SPL iterators, you can
perform iteration of directories. You can create iterators that display directory information,
find files, filter information, load plug-ins, reflect on code, and so on.
Using SplFileObject, you can iterate over the contents of files. With an extended SplFileInfo
class, such as CVSFileObject, you can operate on CSV data, using iterative means. By extending
SplFileInfo, you can create an object similar to SplFileObject. You can utilize any of the standard
SPL filtering and limiting iterators with a CSV file in this manner, which allows you to create a
robust data-parsing system.

McArthur_819-9C11.fm Page 177 Thursday, February 28, 2008 7:49 AM

Free download pdf