Pro PHP- Patterns, Frameworks, Testing and More

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

/path/to/php-src/ext/spl/examples/tree.php

You can also call getPathname() on the $entry SPLFileInfo object if you want to locate only
the path.

RegexFindFile
You can also locate files using a regular expression search. The regular expression is matched
on the entire path and file name, so your patterns should reflect that. Listing 11-8 demonstrates
finding all files that have tree in their name.

Listing 11-8. Using RegexFindFile

require_once('/path/to/php-src/ext/spl/examples/findfile.inc');
require_once('/path/to/php-src/ext/spl/examples/regexfindfile.inc');

$it = new RegexFindFile('/path/to/php-src/ext/spl/examples/', '/tree/');
print_r(iterator_to_array($it));

Array
(
/path/to/php-src/ext/spl/examples/class_tree.php] => SplFileInfo Object
(
)

)

To use this result set, you will most likely want to use the getFilename() method of SplFileInfo
in a value-based loop.

Creating Custom File Filter Iterators.


Creating your own filtering iterators is actually quite simple. All you need to do is create a class
that inherits FilterIterator and implements accept().
The trick is in the constructor; you will presumably want to take a path and a predicate
parameter. To create this constructor, you must receive two parameters, create a
RecursiveDirectoryIterator for the path, and then create a RecursiveIteratorIterator to
pass to the base FilterIterator class, as shown in Listing 11-9.
To operate, the FindFile iterator uses the RecursiveIteratorIterator to get a single-
dimension list of all the files in all subfolders of the underlying RecursiveDirectoryIterator. In
order to create your own filters, such as to find all files by file extension, you first need to flatten
a recursive iterator. Flattening a recursive iterator involves walking the entire tree, and copying
the current name of each step into a nonrecursive list. The flattening of a recursive iterator is
an important part of Listing 11-9, as the filter may work with only a single dimension and not a tree.

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

Free download pdf