The Finder Component (Symfony Docs) (original) (raw)
The Finder component finds files and directories based on different criteria (name, file size, modification time, etc.) via an intuitive fluent interface.
Installation
Note
If you install this component outside of a Symfony application, you must require the vendor/autoload.php
file in your code to enable the class autoloading mechanism provided by Composer. Readthis article for more details.
Usage
The Finder class finds files and/or directories:
The $file
variable is an instance ofSplFileInfo which extends PHP's ownSplFileInfo to provide methods to work with relative paths.
Warning
The Finder
object doesn't reset its internal state automatically. This means that you need to create a new instance if you do not want to get mixed results.
Searching for Files and Directories
The component provides lots of methods to define the search criteria. They all can be chained because they implement a fluent interface.
Location
The location is the only mandatory criteria. It tells the finder which directory to use for the search:
Search in several locations by chaining calls toin():
Use *
as a wildcard character to search in the directories matching a pattern (each pattern has to resolve to at least one directory path):
Exclude directories from matching with theexclude() method:
It's also possible to ignore directories that you don't have permission to read:
As the Finder uses PHP iterators, you can pass any URL with a supportedPHP wrapper for URL-style protocols (ftp://
, zlib://
, etc.):
And it also works with user-defined streams:
See also
Read the PHP streams documentation to learn how to create your own streams.
Files or Directories
By default, the Finder returns both files and directories. If you need to find either files or directories only, use the files() and directories() methods:
If you want to follow symbolic links, use the followLinks()
method:
Note that this method follows links but it doesn't resolve them. Consider the following structure of files of directories:
If you try to find all files in folder1/
via $finder->files()->in('/path/to/folder1/')
you'll get the following results:
- When not using the
followLinks()
method:file1.txt
andfile2link
(this link is not resolved). Thefolder3link
doesn't appear in the results because it's not followed or resolved; - When using the
followLinks()
method:file1.txt
,file2link
(this link is still not resolved) andfolder3/file3.txt
(this file appears in the results because thefolder1/folder3link
link was followed).
Version Control Files
Version Control Systems (or "VCS" for short), such as Git and Mercurial, create some special files to store their metadata. Those files are ignored by default when looking for files and directories, but you can change this with theignoreVCS()
method:
If the search directory and its subdirectories contain .gitignore
files, you can reuse those rules to exclude files and directories from the results with theignoreVCSIgnored() method:
The rules of a directory always override the rules of its parent directories.
Note
Git looks for .gitignore
files starting from the repository root directory. Symfony's Finder behavior is different and it looks for .gitignore
files starting from the directory used to search files/directories. To be consistent with Git behavior, you should explicitly search from the Git repository root.
File Name
Find files by name with thename() method:
The name()
method accepts globs, strings, regexes or an array of globs, strings or regexes:
Multiple filenames can be defined by chaining calls or passing an array:
The notName()
method excludes files matching a pattern:
Multiple filenames can be excluded by chaining calls or passing an array:
File Contents
Find files by content with thecontains() method:
The contains()
method accepts strings or regexes:
The notContains()
method excludes files containing given pattern:
Path
Find files and directories by path with thepath() method:
Use the forward slash (i.e. /
) as the directory separator on all platforms, including Windows. The component makes the necessary conversion internally.
The path()
method accepts a string, a regular expression or an array of strings or regular expressions:
Multiple paths can be defined by chaining calls or passing an array:
Internally, strings are converted into regular expressions by escaping slashes and adding delimiters:
Original Given String | Regular Expression Used |
---|---|
dirname | /dirname/ |
a/b/c | /a\/b\/c/ |
The notPath() method excludes files by path:
Multiple paths can be excluded by chaining calls or passing an array:
File Size
Find files by size with thesize() method:
Restrict by a size range by chaining calls or passing an array:
The comparison operator can be any of the following: >
, >=
, <
,<=
, ==
, !=
.
The target value may use magnitudes of kilobytes (k
, ki
), megabytes (m
, mi
), or gigabytes (g
, gi
). Those suffixed with an i
use the appropriate 2**n
version in accordance with the IEC standard.
File Date
Find files by last modified dates with thedate() method:
Restrict by a date range by chaining calls or passing an array:
The comparison operator can be any of the following: >
, >=
, <
,<=
, ==
. You can also use since
or after
as an alias for >
, and until
or before
as an alias for <
.
The target value can be any date supported by strtotime.
Directory Depth
By default, the Finder recursively traverses directories. Restrict the depth of traversing with depth():
Restrict by a depth range by chaining calls or passing an array:
Custom Filtering
To filter results with your own strategy, usefilter():
The filter()
method takes a Closure as an argument. For each matching file, it is called with the file as a SplFileInfoinstance. The file is excluded from the result set if the Closure returnsfalse
.
The filter()
method includes a second optional argument to prune directories. If set to true
, this method completely skips the excluded directories instead of traversing the entire file/directory structure and excluding them later. When using a closure, return false
for the directories which you want to prune.
Pruning directories early can improve performance significantly depending on the file/directory hierarchy complexity and the number of excluded directories.
Sorting Results
Sort the results by name, extension, size or type (directories first, then files):
Tip
By default, the sortByName()
method uses the strcmp PHP function (e.g. file1.txt
, file10.txt
, file2.txt
). Pass true
as its argument to use PHP's natural sort order algorithm instead (e.g.file1.txt
, file2.txt
, file10.txt
).
The sortByCaseInsensitiveName()
method uses the case insensitivestrcasecmp PHP function. Pass true
as its argument to use PHP's case insensitive natural sort order algorithm instead (i.e. thestrnatcasecmp PHP function)
Sort the files and directories by the last accessed, changed or modified time:
You can also define your own sorting algorithm with the sort()
method:
You can reverse any sorting by using the reverseSorting()
method:
Note
Notice that the sort*
methods need to get all matching elements to do their jobs. For large iterators, it is slow.
Transforming Results into Arrays
A Finder instance is an IteratorAggregate PHP class. So, in addition to iterating over the Finder results with foreach
, you can also convert it to an array with the iterator_to_array function, or get the number of items with iterator_count.
If you call to the in() method more than once to search through multiple locations, pass false
as a second parameter to iterator_to_array to avoid issues (a separate iterator is created for each location and, if you don't pass false
toiterator_to_array, keys of result sets are used and some of them might be duplicated and their values overwritten).
This work, including the code samples, is licensed under aCreative Commons BY-SA 3.0 license.